How to get the FieldInfo of a field from the value

我是研究僧i 提交于 2019-12-12 03:08:18

问题


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



来源:https://stackoverflow.com/questions/28751420/how-to-get-the-fieldinfo-of-a-field-from-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!