Workaround for lack of 'nameof' operator i

2019-01-02 17:57发布

There has been a lot of sentiment to include a nameof operator in C#. As an example of how this operator would work, nameof(Customer.Name) would return the string "Name".

I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.

I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?

I am also interested in a way to implement the functionality of nameof in .NET 2.0 if that is possible.

8条回答
墨雨无痕
2楼-- · 2019-01-02 18:18

The accepted solution is nice, simple and elegant.

However, building an expression tree is expensive, and I need the whole property path.

So I changed it a bit. It is not elegant at all, but it is simple and works well in most cases:

public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
    var s = expression.Body.ToString();
    var p = s.Remove(0, s.IndexOf('.') + 1);
    return p;
}

Example:

? Nameof<DataGridViewCell>.Property(c => c.Style.BackColor.A);
"Style.BackColor.A"
查看更多
爱死公子算了
3楼-- · 2019-01-02 18:25
登录 后发表回答