通过反射调用類的方法,屬性,字段,索引器(2種方法)

本文介绍C#中反射的应用,包括动态调用方法、修改属性和索引器等内容,并提供了详细的代码示例。
Type是System.Reflection功能的根 (Root),也是存取Metadata的主要方法.
使用Type的成員可以取得相關資訊,例如建構函式(Constructor),方法,字段,屬性和類別的事件,以及模組和部署類別的組件(Assembly).

3種取得Type的方法:
1.靜態方法
Type.GetType()
2.運算符
typeof()
3.實例的方法GetType
Employee e=new Employee();
e.GetType()

在一般情況下我們调用的方法並传递给它们的参数,某些情况下可能希望根据用户操作动态调用方法.
通过Reflection命名空间
方法1是使用Type对象上的InvokeMember方法
方法2是使用MethodInfo对象上的Invoke方法

example:
先定義類Employee
其中有靜態屬性Data
實例屬性Name,ID
2個索引器
///<summary>
///自定義類
///</summary>
publicclassEmployee
{
stringname;
intid;

ArrayListlist;

staticintdata;

//instance.ctor()
publicEmployee(intid,Stringname)
{
this.name=name;
this.id=id;

list
=newArrayList();

this.list.Add("001");
this.list.Add("002");
}

//static.ctor()
staticEmployee()
{
data
=119;
}

publicoverridestringToString()
{
return"Id="+id.ToString()+",Name="+name;
}

//instanceMethod"add"
publicstringadd(stringkey1,stringkey2)
{
stringresult=key1+key2;
returnresult;
}

//staticMethod"add"
publicstaticstringadd(stringkey1,stringkey2,stringkey3)
{
returnkey1+key2+key3;
}

publicstringName
{
get
{
returnname;
}
set
{
name
=value;
}
}

publicintID
{
get
{
returnid;
}
set
{
id
=value;
}
}

publicstaticintData
{
get
{
returndata;
}
set
{
data
=value;
}
}

///<summary>
///byindex
///</summary>
publicstringthis[intindex]
{
get
{
returnlist[index].ToString();
}
set
{
list[index]
=value;
}
}

///<summary>
///byvalue
///</summary>
publicstringthis[stringvalues]
{
set
{
this[list.IndexOf(values)]=value;
}
}

}
動態調用:

定義變量
stringresult=String.Empty;
inti;

Typet
=typeof(Employee);

Employeee
=newEmployee(1000,"no1000");


方法1是使用Type对象上的InvokeMember方法:
先動態調用類Employee的實例方法ToString
InvokeMember方法的第一個參數是要調用的方法名稱
第2個參數是位枚舉,代表搜尋的方式
第四個參數是要調用的對象,要是靜態的就用null
第五個參數是要傳送給ToString的數值,由於ToString方法是無參方法,這裡我們送一個空數組new object[]{}
1//callinstanceMethod"ToString"
2result=(typeof(Employee).InvokeMember("ToString",
3BindingFlags.InvokeMethod,
4null,
5e,
6newobject[]{})).ToString();
7Console.WriteLine("instanceMethod'ToString'result={0}",result);
8

再動態調用類Employee的實例方法add,靜態方法add
注意InvokeMember方法的第5個參數代表的是要傳送給add方法的數值
第8個參數代表的是add方法的參數名稱
//callinstanceMethod"add"
result=typeof(Employee).InvokeMember("add",
BindingFlags.InvokeMethod,
null,
e,
newobject[]{"o1","o2"},
null,
null,
newstring[]{"key1","key2"}).ToString();
Console.WriteLine(
"instanceMethod'add'result={0}",result);

//callstaticMethod"add"
result=typeof(Employee).InvokeMember("add",
BindingFlags.InvokeMethod
|BindingFlags.Static|BindingFlags.Public,
null,
null,
newobject[]{"o1","o2","o3"},
null,
null,
newstring[]{"key1","key2","key3"}).ToString();
Console.WriteLine(
"staticMethod'add'result={0}",result);
Console.WriteLine();

再修改靜態屬性Data,把它從119修改為911
1//callstaticProperty
2i=(int)typeof(Employee).InvokeMember("Data",
3BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Static,
4null,
5null,
6newobject[]{});
7Console.WriteLine("staticProperty'Data'={0}",i);
8
9//updatestaticProperty
10typeof(Employee).InvokeMember("data",
11BindingFlags.SetField|BindingFlags.NonPublic|BindingFlags.Static,
12null,
13null,
14newobject[]{911});
15Console.WriteLine("updatestaticProperty");
16
17//callstaticProperty
18i=(int)typeof(Employee).InvokeMember("Data",
19BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Static,
20null,
21null,
22newobject[]{});
23Console.WriteLine("againcallstaticProperty'Data'={0}",i);
24Console.WriteLine();
25

再修改實例屬性Name,把它從no 1000修改為w
1//readinstanceProperty
2result=typeof(Employee).InvokeMember("Name",
3BindingFlags.GetProperty,
4null,
5e,
6newobject[]{}).ToString();
7Console.WriteLine("instanceProperty'Name'={0}",result);
8
9//updateinstanceproperty
10typeof(Employee).InvokeMember("name",
11BindingFlags.SetField|BindingFlags.NonPublic|BindingFlags.Instance,
12null,
13e,
14newobject[]{"w"});
15Console.WriteLine("updateinstanceproperty");
16
17//againcallreadinstanceProperty
18result=typeof(Employee).InvokeMember("Name",
19BindingFlags.GetProperty,
20null,
21e,
22newobject[]{}).ToString();
23Console.WriteLine("againcallinstanceProperty'Name'={0}",result);
24Console.WriteLine();
25

再修改索引器,把索引器的第2個(index[1])內容修改為222
注意修改索引器的InvokeMember方法,第5個參數的數組new object[]{"002","222"}
将要设置元素的索引值放在对象数组的第一个元素中,将要设置的值作为第二个元素
1//callindex[1]
2result=typeof(Employee).InvokeMember("Item",
3BindingFlags.GetProperty,
4null,
5e,
6newobject[]{1}).ToString();
7Console.WriteLine("index[1]={0}",result);
8
9//updateindex[1]
10typeof(Employee).InvokeMember("Item",
11BindingFlags.SetProperty,
12null,
13e,
14newobject[]{"002","222"});
15Console.WriteLine("updateindex[1]");
16
17//againcallindex[1]
18result=typeof(Employee).InvokeMember("Item",
19BindingFlags.GetProperty,
20null,
21e,
22newobject[]{1}).ToString();
23
24Console.WriteLine("againcallindex[1]={0}",result);
25Console.WriteLine();
26

方法2是使用MethodInfo对象上的Invoke方法:
1//callInstanceMethod'add'
2MethodInfomethodInfo1=t.GetMethod("add",BindingFlags.Instance|BindingFlags.Public);
3//InstanceMethod,firstparameterisoneInstance
4result=methodInfo1.Invoke(newEmployee(1,""),newobject[]{"key1","key2"}).ToString();
5Console.WriteLine("callInstanceMethod'add'result={0}",result);
6
7//callStaticMethod'add'
8MethodInfomethodInfo2=t.GetMethod("add",BindingFlags.Static|BindingFlags.Public);
9//StaticMethod,firstparameterisNull
10result=methodInfo2.Invoke(null,newobject[]{"key1","key2","key3"}).ToString();
11Console.WriteLine("callStaticMethod'add'result={0}",result);
12


結果圖片:




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值