开发者

Adding nameof to C# through backdoors

开发者 https://www.devze.com 2023-01-19 23:17 出处:网络
Well, I am not alone who is being sick of magical strings which are constantly used just to do data binding -- see:

Well, I am not alone who is being sick of magical strings which are constantly used just to do data binding -- see:

How to make Databinding type safe and support refactoring

However I am concerned with performance of this solution and much more typing -- each time you would like to use nameof you have to type a lambda. So I am thinking of more brute-force method -- writing a function nameof and external program, that will change each .cs file before it is compiled.

public string nameof<T>(T obj,string name = null)
{
  return name;
}

You would use it this way

nameof(the_object.MyProperty);

The key lies in external program helping nameof -- it would search for any call of the nameof, and simply replace

nameof(X.Y.Z)

or

nameof(X.Y.Z,"s")

into

n开发者_如何转开发ameof(X.Y.Z,"Z")

My question is -- what limitations, pitfalls of this approach do you see? Or maybe .Net 5.0 with built-in nameof will be shipped next week, so it make no sense to start writing a program for it? ;-)

Thank you in advance for your thoughts, recommendations, and so on.


Doing any pre-compilation code changes would be an extreme hassle. So I would avoid it.

I wouldn't worry too much about performance - most times when you need a property name as a string you'll end up doing reflection or IO anyway, so performance is going to be relatively slow anyway.

Here's what I suggest to use:

public static string ToPropertyName<T>(this Expression<Func<T>> @this)
{
    var @return = string.Empty;
    if (@this != null)
    {
        var memberExpression = @this.Body as MemberExpression;
        if (memberExpression != null)
        {
            @return = memberExpression.Member.Name;
        }
    }
    return @return;
}

Now you can do this:

Expression<Func<T>> px = x => x.Foo;
var pn = px.ToPropertyName(); // == "Foo"
0

精彩评论

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