直接上代码了:
class MyClass
{
private int Count; public int Count_
{
get { return Count; }
set { Count = value; }
} public MyClass(int count)
{
Count = count;
} public void method1()
{
Console.WriteLine("Called method1");
} public static int method2(int x)
{
return x * x;
} public void method3(int x, double y)
{
Console.WriteLine("method3 is Called, x:{0} ,y:{1}",x,y);
} public void method4()
{
Console.WriteLine("method4 is Called, {0}",Count);
} private static string method5(double x) //私有静态方法,不能直接调用,但可以绑定到委托
{
return Math.Sqrt(x).ToString();
} } class Program
{
static void Main(string[] args)
{
/*取得Myclass的Type对象*/
Type t=typeof(MyClass);
/*通过Activator实例化MyClass对象,供实例方法来调用*/
Object obj = Activator.CreateInstance(t,new object[]{88});
/*获取所有的方法列表*/
MethodInfo[] methods = t.GetMethods(); foreach (MethodInfo me in methods)
{
Console.WriteLine(me.ToString());
if (me.Name == "method1")
me.Invoke(obj ,null);
if(me.Name=="method2")
me.Invoke(null,new object[]{10});
} MethodInfo m = t.GetMethod("method3");
m.Invoke(obj,new object[]{123,0.677}); /*Creates a delegate of the specified type that represents
* the specified static method of the specified class.*/
/*建立泛型委托,调用私有静态方法*/
Delegate del = Delegate.CreateDelegate(typeof(Func<double,string>),t,"method5"); // Console.WriteLine("Call delegate with method5 Sqrt(2)={0}",(Func<double,string>)del(2)); /*这行代码老是提示del是局部变量,但是勿当方法使用,该怎么改写代码就可以调用*/
Console.Read();
}
}
C# 反射机制delegate
class MyClass
{
private int Count; public int Count_
{
get { return Count; }
set { Count = value; }
} public MyClass(int count)
{
Count = count;
} public void method1()
{
Console.WriteLine("Called method1");
} public static int method2(int x)
{
return x * x;
} public void method3(int x, double y)
{
Console.WriteLine("method3 is Called, x:{0} ,y:{1}",x,y);
} public void method4()
{
Console.WriteLine("method4 is Called, {0}",Count);
} private static string method5(double x) //私有静态方法,不能直接调用,但可以绑定到委托
{
return Math.Sqrt(x).ToString();
} } class Program
{
static void Main(string[] args)
{
/*取得Myclass的Type对象*/
Type t=typeof(MyClass);
/*通过Activator实例化MyClass对象,供实例方法来调用*/
Object obj = Activator.CreateInstance(t,new object[]{88});
/*获取所有的方法列表*/
MethodInfo[] methods = t.GetMethods(); foreach (MethodInfo me in methods)
{
Console.WriteLine(me.ToString());
if (me.Name == "method1")
me.Invoke(obj ,null);
if(me.Name=="method2")
me.Invoke(null,new object[]{10});
} MethodInfo m = t.GetMethod("method3");
m.Invoke(obj,new object[]{123,0.677}); /*Creates a delegate of the specified type that represents
* the specified static method of the specified class.*/
/*建立泛型委托,调用私有静态方法*/
Delegate del = Delegate.CreateDelegate(typeof(Func<double,string>),t,"method5"); // Console.WriteLine("Call delegate with method5 Sqrt(2)={0}",(Func<double,string>)del(2)); /*这行代码老是提示del是局部变量,但是勿当方法使用,该怎么改写代码就可以调用*/
Console.Read();
}
}
C# 反射机制delegate
==>
((Func<double,string>)del)(2)
试试。