Win8 UT 的时候发现GetRuntimeMethod()无法访问一个class的private方法,只用通过IEnumerable<>枚举才可以,所以纪律一下。
class CForTest
{
private int Increase1(int i) { return ++i; }
public int Increase2(int i) { return ++i; }
}
public void Test()
{
CForTest forTest = new CForTest();
//
Type t = typeof(CForTest);
MethodInfo mi_Inc1 = t.GetRuntimeMethod("Increase1", new Type[] { typeof(int) }); // fail
MethodInfo mi_Inc2 = t.GetRuntimeMethod("Increase2", new Type[] { typeof(int) }); // success
IEnumerable<MethodInfo> mList = t.GetRuntimeMethods();
MethodInfo mi_private = null;
foreach (var m in mList)
{
if (m.Name.Equals("Increase1"))
{
mi_private = m;
break;
}
}
if (mi_private != null)
{
object ret = mi_private.Invoke(forTest, new Object[] { 100 });
}
//
}