I have recently read the whole concepts of Reflection and I know the main idea of using this instrument of C# But i still can not understand one of it's aspects. I think,Encapsulation does not have any meaning,if anyone has this ability to execute a private method through reflection.Would you mind letting me know about this misunderstanding ?
Calling a private method using reflection
string methodName = "";
Type aclass = typeof (AClass);
object obj = Activator.CreateInstance(aclass);
Type t = typeof (AClass);
MethodInfo [] mi = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
methodName = mi[0].Name;
MethodInfo PrivateMethod = typeof (AClass).GetMethod(methodName,BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine(PrivateMethod.Invoke(obj,null));
Console.ReadLine();
Class AClass has a private method
internal class AClass
{
private bool First()
{
return true;
}
}
Output :
True