How to get the FieldInfo of a field from the value

2019-09-07 14:40发布

问题:

I want to access the FieldInfo, for the CustomAttributes that are on a field, and other purposes, but I'd prefer not to use a string to access that field, nor to have to run through all the fields in a class.

If I simply have,

class MyClass
{
#pragma warning disable 0414, 0612, 0618, 0649
    private int myInt;
#pragma warning restore 0414, 0612, 0618, 0649

    public MyClass()
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
        Console.WriteLine( GetType().GetField("myInt", flags) );

        foreach( FieldInfo fi in GetType().GetFields(flags) )
        {
            Console.WriteLine( string.Format("{0} {1} {2}", fi.Name, myInt, fi.GetValue(this) ) );
        }
    }
}

I know I can access the FieldInfo of "myInt" directly via the "GetField" function, if I have the string of it's name, or cycling through "GetFields", that would again rely upon having the string "myInt" to ensure you've the right field.

Is there any sort of magic that's available like ref myInt, or out myInt, or some keyword that I don't know about yet which would give me access, or am I limited to needing the string name to get it?

回答1:

Do you mean getting the memberinfo from a compiled expression rather than the string? e.g

class Program
{
    public static void Main()
    {
        var cls = new MyClass();
        Console.WriteLine(GetMemberInfo(cls, c => c.myInt));
        Console.ReadLine();
    }

    private static MemberInfo GetMemberInfo<TModel, TItem>(TModel model, Expression<Func<TModel, TItem>> expr)
    {
        return ((MemberExpression)expr.Body).Member;
    }

    public class MyClass
    {
        public int myInt;   
    }


}


回答2:

In C# 6 (you can get the CTP here) there is the nameof(...) operator - you'd use:

string name = nameof(myInt);
var fieldInfo = GetType().GetField(name, flags);

Is that an option for you, or must you use C# 5.0 (.NET 4.5)?