通过Invoke反射类的private方法
前些时间需要写个方法来handle一个类的所有private方法,晚上查了一大片都没有找到,有些无聊的人竟然危言耸听地说不可能handle到private方法。最后还是自己写了一个出来,供有需要的人分享一下。
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Linq;
namespace BruceReflection
{
class Program
{
static void Main(string[] args)
{
BruceTest.Show();
BruceTest.TestPrivate();
Console.Read();
}
}
public class BruceTest
{
/// <summary>
/// 测试反射private方法
/// </summary>
public static void TestPrivate()
{
Bruce b = new Bruce();
Type t = b.GetType();
MethodInfo [] ms;
MethodInfo m;
BindingFlags bf = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
ms = t.GetMethods(bf);
m =(from p in ms where p.Name =="PrivateMethod" select p).First () ;//如果你使用的VS版本不支持linq,则这里可以改成用循环来筛选
//反射private方法
m.Invoke(b, new object[] {"Bruce Lee" });
}
public static void Show()
{
Bruce b = new Bruce();
Type t = b.GetType();
MethodInfo [] ms;
BindingFlags bf;
//遍历所有实例化的方法
foreach (BindingFlags f in Enum.GetValues(typeof(BindingFlags)))
{
bf = BindingFlags.InvokeMethod| BindingFlags.Instance ;
bf |= f;
ms = t.GetMethods(bf);
if (ms != null && ms.Length > 0)
{
Console.WriteLine("BindingFlag is " + bf.ToString());
ShowMethodInfo(ms);
}
}
//遍历所有静态方法
foreach (BindingFlags f in Enum.GetValues(typeof(BindingFlags)))
{
bf = BindingFlags.InvokeMethod | BindingFlags.Static ;
bf |= f;
ms = t.GetMethods(bf);
if (ms != null && ms.Length > 0)
{
Console.WriteLine("BindingFlag is " + bf.ToString());
ShowMethodInfo(ms);
}
}
}
public static void ShowMethodInfo(MethodInfo[] ms)
{
foreach (MethodInfo m in ms)
{
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine("/tMethod name : {0} /n/treturn type : {1} ",m.Name, m.ReturnType);
ShowParameterInfo(m.GetParameters());
}
Console.WriteLine("*************************************************************/n");
}
public static void ShowParameterInfo(ParameterInfo [] ps)
{
foreach (ParameterInfo p in ps)
{
Console.WriteLine("/t/tParam name : {0}, type : {1}", p.Name, p.ParameterType );
}
}
}
public class Bruce
{
private string _PrivateAttribute="This is a private attribute";
public string PublicAttribute="This is a public attribute";
private void PrivateMethod(string arg)
{
Console.Write("This is a private method! arg is " + arg);
}
public void PublicMethod(string arg1,int arg2)
{
Console.Write("This is a public method! arg1 is {0},arg2 is {1}. " , arg1,arg2 );
}
private static string static_private_Method(string arg)
{
return ("This is a static and private method! arg is " + arg);
}
public static string Static_Public_Method(string arg)
{
return ("This is a static and public method! arg is " + arg);
}
protected string protected_Method(string arg)
{
return ("This is a protected! arg is " + arg);
}
}
}