Question

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?

Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top