c# - 如何避免使用反射访问类的私有(private)成员?

标签 c# security reflection

我正在阅读 Security Considerations for Reflection我看到了以下行:

Transparent code cannot use reflection to access security-critical members, even if the code is fully trusted. A MethodAccessException, FieldAccessException, or TypeAccessException is thrown.

所以,我写了一个测试程序:

类库:

namespace ClassLibrary
{
    public class Foo
    {
        [SecurityCritical] private int X;
    }
}

测试程序:

using ClassLibrary;
namespace ReflectionSecurityTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Foo f = new Foo();
            var flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var field = f.GetType().GetField("X", flags);
            field.SetValue(f,15);
            Console.WriteLine(field.GetValue(f));
        }
    }
}

我希望看到异常,但我在控制台中看到了 15。问题是为什么?是我误解了 SecurityCritical 的作用还是我做错了什么?

最佳答案

下面的要点指出:

  • Code that is running with partial trust is treated as transparent.

Application code that is run from the command line runs with full trust. As long as it is not marked as transparent, it can use reflection to access security-critical members. When the same code is run with partial trust (for example, in a sandboxed application domain) the assembly's trust level determines whether it can access security-critical code: If the assembly has a strong name and is installed in the global assembly cache, it is a trusted assembly and can call security-critical members. If it is not trusted, it becomes transparent even though it was not marked as transparent, and it cannot access security-critical members.

所以回答标题中的问题:

How can I avoid accessing private members of a class using Reflection?

如果您不能将执行反射的代码沙箱化,您就不能。

关于c# - 如何避免使用反射访问类的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876813/

相关文章:

c# - 通过 Unity 中的脚本更改作为 2D Sprite 子项的 TextMeshPro 文本

c# - 内置类型的依赖注入(inject)

security - delphi exe的内部密码安全吗?

wcf - 在哪里可以找到 WS-Trust 的 U-Prove 实现?

c# - 使用存储库模式实现 WCF 数据服务

c# - 如何将 MemoryStream 转换为 FileStream?

java - JRuby 中的安全级别

c# - 创建一个新的 AnonymousType 实例

java - 与 new 关键字相比,使用 Class.forName() 加载实例有什么优势?

c# - 为什么使用反射无法使用继承接口(interface)的成员?