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?

有帮助吗?

解决方案

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);

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top