在以下代码中尝试使用反射访问 protected 字段时,为什么我会收到 FieldAccessException
?
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
Foo foo = new Foo();
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.NonPublic
| BindingFlags.Public | BindingFlags.Static;
FieldInfo fieldInfo = foo.GetType().GetField("field", bindFlags);
Object fieldValue = fieldInfo.GetValue(foo);
}
}
public class Foo
{
public Foo() {
field = 1;
}
protected int field;
}
这个 fiddle 给了我异常(exception):https://dotnetfiddle.net/wu5vDX ,但绑定(bind)标志不应该确保我能够访问该字段吗?
编辑:显然,这是 .Net Fiddle 独有的结果。例如,它只发生在 fiddle 中,而不是在 Visual Studio 中。
最佳答案
这是DotNetFiddle施加的限制通过不在 Full Trust 中运行代码(出于安全原因)。因此,您无法利用 Reflection API 的所有功能。
来自 MSDN :
..., only trusted code can use reflection to access nonpublic members that would not be directly accessible to compiled code.
关于c# - 通过反射访问 protected 字段时出现 FieldAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560660/