【C#反射】Type的用法
c# Type.InvokeMember用法
publicobjectInvokeMember(string,BindingFlags,Binder,object,object[]);
string:你所要呼叫的函式名
BindingFlags:你所要呼叫的函式的屬性,可以組合
Binder:高階內容,可以先不看
object:呼叫該成員函式的例項
object[]:引數,
下面是msdn例子:
//呼叫公有靜態成員函式(不帶引數)
Typet=typeof(TestClass);
t.InvokeMember("SayHello",BindingFlags.Public|BindingFlags.InvokeMethod|BindingFlags.Static,null,null,newobject[]{});
//呼叫例項的函式(不帶引數),第三個引數為該例項
TestClassc=newTestClass();
c.GetType().InvokeMember("AddUp",BindingFlags.Public|BindingFlags.InvokeMethod,null,c,newobject[]{});
c.GetType().InvokeMember("AddUp",BindingFlags.Public|BindingFlags.InvokeMethod,null,c,newobject[]{});
//呼叫帶引數的函式,
//方法是:將你的所有引數都放到一個object的數組裡面
object[]args=newobject[]{100.09,184.45};
objectresult;
result=t.InvokeMember("ComputeSum",BindingFlags.Public|BindingFlags.InvokeMethod|BindingFlags.Static,null,null,args);
Console.WriteLine("{0}+{1}={2}",args[0],args[1],result);
//獲得一個屬性值
result=t.InvokeMember("Name",BindingFlags.Public|BindingFlags.GetField,null,c,newobject[]{});
Console.WriteLine("Name=={0}",result);
//設定一個屬性值
t.InvokeMember("Name",BindingFlags.Public|BindingFlags.SetField,null,c,newobject[]{"NewName"});
result=t.InvokeMember("Name",BindingFlags.Public|BindingFlags.GetField,null,c,newobject[]{});
Console.WriteLine("Name=={0}",result);
//獲得一個下標屬性值([])
intindex=3;
result=t.InvokeMember("Item",BindingFlags.Public|BindingFlags.GetProperty,null,c,newobject[]{index});
Console.WriteLine("Item[{0}]=={1}",index,result);
//設定一個下標屬性值([])
index=3;
t.InvokeMember("Item",BindingFlags.Public|BindingFlags.SetProperty,null,c,newobject[]{index,"NewValue"});
result=t.InvokeMember("Item",BindingFlags.Public|BindingFlags.GetProperty,null,c,newobject[]{index});
Console.WriteLine("Item[{0}]=={1}",index,result);
//獲得一個屬性或者是成員變數的值
//也就是,假設有一個類是這樣的:
//classtemp{
//publicstringname;
//publicstringName{
//get{returnname;}
//set{name=value}
//}
//}
//那麼通過一下語句就可獲得Name的值,
result=t.InvokeMember("Name",BindingFlags.Public|BindingFlags.GetField|BindingFlags.GetProperty,null,c,newobject[]{});
Console.WriteLine("Name=={0}",result);
//通過一下,語句可以獲得name的值
result=t.InvokeMember("name",BindingFlags.Public|BindingFlags.GetField|BindingFlags.GetProperty,null,c,newobject[]{});
Console.WriteLine("Value=={0}",result);
//呼叫一個函式,使用引數名對應的引數
object[]argValues=newobject[]{"Mouse","Micky"};
String[]argNames=newString[]{"lastName","firstName"};
t.InvokeMember("PrintName",BindingFlags.Public|BindingFlags.InvokeMethod,null,null,argValues,null,null,argNames);
//呼叫一個型別的預設函式,好像在C#裡面沒有預設成員函式
Typet3=typeof(TestClass2);
t3.InvokeMember("",BindingFlags.Public|BindingFlags.InvokeMethod,null,newTestClass2(),newobject[]{});
//InvokingaByRefmember
MethodInfom=t.GetMethod("Swap");
args=newobject[2];
args[0]=1;
args[1]=2;
m.Invoke(newTestClass(),args);