Why am I getting a FieldAccessException
when trying to access a protected field with reflection in the following code?
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;
}
This fiddle gives me the exception: https://dotnetfiddle.net/wu5vDX, but shouldn't the binding flags make sure that I am able to access the field?
Aucun commentaire:
Enregistrer un commentaire