----反射的一种用法

using  System; 
using  System.Reflection; 
using  System.Globalization; 
 
public   class  MyClass 

    
private   string  myString; 
    
public  MyClass() 
    { 
        myString 
=   " Old value "
    } 
    
string  GetField 
    { 
        
get  
        { 
            
return  myString; 
        } 
    } 

 
public   class  FieldInfo_SetValue 

    
public   static   void  Main() 
    { 
        
try  
        { 
            MyClass myObject 
=   new  MyClass(); 
            Type myType 
=  Type.GetType( " MyClass " ); 
             FieldInfo myFieldInfo 
=  myType.GetField( " myString " , BindingFlags.NonPublic  |  BindingFlags.Instance);  
            
//  Display the string before applying SetValue to the field. 
            Console.WriteLine(  "  The field value of myString is {0}. " , myFieldInfo.GetValue(myObject));  
            
//  Display the SetValue signature used to set the value of a field. 
            Console.WriteLine(  " Applying SetValue(Object, Object). " );     
            
//  Change the field value using the SetValue method.  
            myFieldInfo.SetValue(myObject,  " New value " );  
            
//  Display the string after applying SetValue to the field. 
            Console.WriteLine(  " The field value of mystring is {0}. " , myFieldInfo.GetValue(myObject)); 
            
//  Set the field value to its old value.  
            myFieldInfo.SetValue( myObject ,  " Old value "  );  
            myFieldInfo 
=  myType.GetField( " myString " , BindingFlags.NonPublic  |  BindingFlags.Instance);  
            
//  Display the string before applying SetValue to the field. 
            Console.Write(  "  The field value of mystring is {0}.  " , myFieldInfo.GetValue(myObject));  
            
//  Display the SetValue signature used to set the value of a field. 
            Console.WriteLine( " Applying SetValue(Object, Object, BindingFlags, Binder, CultureInfo). " );  
            
//  Change the field value using the SetValue method.  
            myFieldInfo.SetValue(myObject,  " New value " , BindingFlags.Public,  null null );      
            
//  Display the string after applying SetValue to the field. 
            Console.WriteLine(  " The field value of mystring is {0}. " , myFieldInfo.GetValue(myObject)); 
        } 
        
catch ( Exception e ) 
        { 
            
//  Any exception generated is displayed.  
            Console.WriteLine(  " Exception: {0} " , e.Message ); 
        } 
    } 

 

===============================
http://kb.cnblogs.com/page/42051/

http://kb.cnblogs.com/page/42279/

 

转载于:https://www.cnblogs.com/simhare/archive/2009/07/11/1520867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值