.NET Core 1.1如何获取当前属性的名称

How to get the name of the current property in .NET Core 1.1

我需要能够在 .NET Core 中的 class 上访问当前 属性 的名称。

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get => _myProperty;
        set
        {
            // GOAL: Check my property name and then do something with that information. 

            // The following used to works in the full .NET Framework but not .NET Core.
            // var propName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            _myProperty = value;
        }
    }
}

在完整的 .NET Framework 中,我们可以像下面这样使用反射。

System.Reflection.MethodBase.GetCurrentMethod().Name;

(我们记得 属性 实际上只是一种底层方法。)

但是,似乎此功能在 .NET Core 1.1 中不可用——尽管它 (may/will) 在 .NET Standard 2.0 中可用。

在这个 GitHub 问题 (https://github.com/dotnet/corefx/issues/12496) 上,有一个关于使用 GetMethodInfoOf 访问 属性 名称的参考。但是,我无法找到此方法的任何示例,指向可能示例的 GitHub link 似乎已损坏。

还有什么其他策略或技术可以用来检索当前 属性 的名称?

非常感谢!

也许我完全误解了你的问题,但是简单地使用 nameof 运算符呢?

var propName = nameof(MyProperty);