简体   繁体   English

通过早期版本的C#中C#6的nameof功能代码实现部分实现?

[英]Partial implemention through code of C#6's nameof functionality in earlier versions of C#?

"nameof" is an amazing idea which would be good to replicate in previous versions even if partially. “ nameof”是一个了不起的想法,即使部分复制,也可以在以前的版本中很好地复制。

I am particularly interested in public property names like: 我对以下公共财产名称特别感兴趣:

public class MyClass
{
    public SomeType Myproperty {get;set;}
}


static Main()
{
    MyClass myClass = new MyClass();

    Console.WriteLine(Utilities.NameOf(myClass.MyProperty)); //Writes "MyProperty".
    Console.ReadKey();
}

Is there a way to do this (maybe through reflection etc.)? 有没有办法做到这一点(也许通过反射等)? If we could do this, it would also prepare our code for when we upgrade to C#6 in the future by simply replacing Utilities.NameOf with nameof. 如果我们能够做到这一点,它还将为将来将来升级到C#6时准备代码,只需用nameof替换Utilities.NameOf。

Thanks to Alexei Levenkov for pointing to the right direction, 感谢Alexei Levenkov指出正确的方向,

Schotime 's for his answer in this question and Schotime 对此问题的回答是,

agent-j 's for his answer in this question agent-j这个问题上的回答

there is a simple and elegant solution that has two versions: 有一个简单而优雅的解决方案,有两个版本:

public static class Util
{
    public static string NameOf<TProperty>(Expression<Func<TProperty>> e)
    {
        return (e.Body as MemberExpression).Member.Name;
    }

    public static string NameOf<TClass, TProperty>(Expression<Func<TClass, TProperty>> e)
    {
        return (e.Body as MemberExpression).Member.Name;
    }
}

and can be used so: 可以这样使用:

public class MyClass
{
    public SomeProperty MyProperty { get; set; }
}


static void Main(string[] args)
{
    MyClass myClass = new MyClass();


    string case1 = Util.NameOf(() => myClass.MyProperty);       //Case1 when an instance is available 250x
    string case2 = Util.NameOf(() => (null as MyClass).MyProperty); //Case2 when no instance is available 175x
    string case3 = Util.NameOf((MyClass c) => c.MyProperty);        //Case3 when no instance is available 330x

    string caseTest = "MyProperty";     //Test case 1x

}

At the end of each case, the number shows how much slower each call is relative to a literal string assignment. 在每种情况的结尾,数字显示相对于文字字符串分配而言,每个调用的速度要慢多少。

This was done by assigning the return values of each call to an array of strings and comparing that to the literal string assignment of the same value "MyProperty" . 这是通过将每个调用的返回值分配给字符串数组并将其与具有相同值"MyProperty"的文字字符串分配进行比较来完成的。

Case2 seems to be the winner. Case2似乎是赢家。

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

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