How does nameof work?

穿精又带淫゛_ 提交于 2019-12-22 04:21:26

问题


I was just wondering how come nameof from C# 6, can access non static property just like if it was static. Here is an example

public class TestClass
{
    public string Name { get; set; }
}

public class Test
{
    public Test()
    {
        string name = nameof(TestClass.Name); // whats so speciall about nameof
        //string name2 = TestClass.Name; this won't compile obviously, 
    }
}

回答1:


It's not "accessing" the property - that operator is purely a compiler mechanism to inject the "name" of the argument into the code. In this case it will replace nameof(TestClass.Name) with "Name". The fact that it's non-static is irrelevant.




回答2:


nameof Interpreter gets resolved at compiletime and translated to a static string instead.
In your case nameof(TestClass.Name) you will only return "Name" as a string.
You have to use nameof(TestClass).
With nameof you can minimize redundancy in your code (For instance: you dont have to define a string for a propertyname or something like this by using nameof.

You can also use it to represent a classes name. But be aware! nameof(MyClass)
may not be the same as at runtime if you have an derived class! For runtime purposes use typeOf or .GetType() instead.

Read more at MSDN



来源:https://stackoverflow.com/questions/39427076/how-does-nameof-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!