C#通过反射可以调用类的私有成员吗 why
如何使用反射调用私有方法的例子:using System;
using System.Reflection;
using System.Collections.Generic;
public class A
{
private void method () {Console.WriteLine( "I am a private method in class A");}
}
public class B
{
public void method () {Console.WriteLine( "I am a public method in class B");}
}
public class MyClass
{
public static void Main()
{
RL();
Console.WriteLine ("\nReflection.MethodInfo\n");
A MyA = new A();
B MyB = new B();
// Get the Type and MethodInfo.
Type t = typeof(A);
MethodInfo mi1 = t.GetMethod("method", BindingFlags.NonPublic | BindingFlags.Instance);
mi1.Invoke(MyA, null);
Type tt = typeof(B);
MethodInfo mi2 = tt.GetMethod("method");
mi2.Invoke(MyB, null);
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
c++中说过,类的外部不能直接调用类的私有成员啥!
为什么C#通过反射就可以调用了呢??上面是我从网上找到的一篇文章