问题
Solely for the sake of example I've written this:
public class MyClass
{
private int MyMethod()
{
return 1;
}
}
Is there any way to change access modifier of MyClass::MyMethod()
in runtime to public using Reflection or something else and then invoke it?
回答1:
Not really sure if you can modify the access specifier, but you can call the private method through reflection like:
MyClass instance = new MyClass();
MethodInfo yourMethod = instance
.GetType()
.GetMethod("MyMethod", BindingFlags.NonPublic | BindingFlags.Instance);
var returnValue = yourMethod.Invoke(instance, new object[] { });
Console.WriteLine(returnValue);
回答2:
No, a class is what it is and you can't change it at runtime.
You could create a new class that has the members, except that MyMethod
would be public, but it wouldn't be the same class anymore.
In any case, I can't think of any situation where doing something like this would make any kind of sense.
来源:https://stackoverflow.com/questions/19325361/change-the-access-modifier-in-runtime