简体   繁体   English

如何从值中获取字段的FieldInfo

[英]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. 我想访问FieldInfo,用于字段上的CustomAttributes以及其他目的,但我不想使用字符串访问该字段,也不必遍历类中的所有字段。

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. 我知道我可以直接通过“ GetField”函数访问“ myInt”的FieldInfo,如果我有其名称的字符串,或者循环通过“ GetFields”,那将再次依赖于字符串“ myInt”来确保您ve正确的字段。

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? 是否可以使用ref myIntout myInt ,或者我不知道的某个关键字可以访问我,还是我仅限于需要字符串名称来获得它?

Do you mean getting the memberinfo from a compiled expression rather than the string? 您的意思是从编译表达式而不是字符串中获取memberinfo吗? 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: C#6 (您可以在此处获得CTP)中,有nameof(...)运算符-您将使用:

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)? 这是您的一个选择,还是必须使用C#5.0(.NET 4.5)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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