开发者

C# equivalent of typeof for fields

开发者 https://www.devze.com 2022-12-29 21:13 出处:网络
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.

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.

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)? 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, an开发者_运维百科d I want to display them in a DataGridView, but I only want displayed columns for certain fields. 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: e.g., using foo = System.Collections.Generic.List;

0

精彩评论

暂无评论...
验证码 换一张
取 消