在运行时更改访问修饰符 [英] Change the access modifier in runtime

查看:85
本文介绍了在运行时更改访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅出于示例目的,我这样写:

Solely for the sake of example I've written this:

public class MyClass
{
    private int MyMethod()
    {
        return 1;
    }
}

是否有任何方式使用反射或其他方法将运行时 MyClass :: MyMethod()的访问修饰符更改为 public ,然后调用它?

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

这篇关于在运行时更改访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆