C # equivalent of typeof for fields

With reflection, you can find a class from a string at runtime, 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 find it from a string at runtime, but if you want to check the type of compilation time, etc., 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, and not to search for a string at run time.

edit: an example of what I want to use for this, let's say I have a list of objects that may have been read from the database, and I want to display them in a DataGridView, but I only need the displayed columns for certain fields. I would like to write a method something like:

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

and be able to call him like

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

Such an idea.

+3
source share
2 answers

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);
+5
source

Not for the fields. The closest you can get is "using an alias", which allows you to specify alternative names for types: for example, using foo = System.Collections.Generic.List;

0
source

Source: https://habr.com/ru/post/1744252/


All Articles