简体   繁体   English

C#相当于字段的typeof

[英]C# equivalent of typeof for fields

With reflection, you can look up a class from a string at run time, but you can also say typeof(Foo) and get compile time type checking, auto completion etc. 使用反射,您可以在运行时从字符串中查找类,但您也可以说typeof(Foo)并获得编译时类型检查,自动完成等。

If what you want is a field not a class, you can look it up from a string at runtime, but if you want compile time type checking etc., is there anyway to say something like fieldof(Foo.Bar)? 如果你想要的是一个字段而不是一个类,你可以在运行时从一个字符串中查找它,但如果你想要编译时类型检查等,那么无论如何要说像fieldof(Foo.Bar)? I know the name of both the class and the field in advance, and I want to be able to refer to the field at compile time rather than with a run-time string lookup. 我事先知道了类和字段的名称,我希望能够在编译时引用该字段而不是运行时字符串查找。

edit: An example of what I want to use this for, say I've got a list of objects that may have been read from a database, and I want to display them in a DataGridView, but I only want displayed columns for certain fields. 编辑:我想要使用它的一个例子,比如我有一个可能已从数据库中读取的对象列表,我想在DataGridView中显示它们,但我只想显示某些字段的列。 I'd like to write a method something like: 我想写一个类似的方法:

void DisplayData(object[] objs, params FieldInfo[] fields)

and be able to call it like 并能够称之为

DisplayData(accounts, fieldof(Account.Name), fieldof(Account.Email));

That sort of idea. 那种想法。

You can get rid of string literals using expressions 您可以使用表达式删除字符串文字

public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
{
    MemberExpression memberExpression = null;

    if (expression.Body.NodeType == ExpressionType.Convert)
    {
        memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
    }
    else if (expression.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpression = expression.Body as MemberExpression;
    }

    return memberExpression.Member as PropertyInfo;
}

// usage:
PropertyInfo p = GetProperty<MyClass>(x => x.MyCompileTimeCheckedPropertyName);

Not for fields. 不适合田野。 The closest you can get is a 'using alias' which allows you to specify alternative names for types: eg, using foo = System.Collections.Generic.List; 您可以获得的最接近的是“使用别名”,它允许您为类型指定替代名称:例如,使用foo = System.Collections.Generic.List;

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

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