简体   繁体   中英

How to get the FieldInfo of a field from the value

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?

Do you mean getting the memberinfo from a compiled expression rather than the string? eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM