如何从该属性的getter/setter中获取属性名称?

Nam*_* VU 8 c# properties

假设我们有一个属性如下

public string SomeProperty
{
    get
    {
        var propName = "SomeProperty";
        return "<" + propName + ">";
    }
}
Run Code Online (Sandbox Code Playgroud)

如何propName通过读取程序集信息本身将上述变量的值设置为属性名称?

编辑

为什么我们需要这个?

我正在使用这里d:DataContext提到的WPF ,这将帮助我显示绑定属性的"设计模式"值 - 通常,绑定值在设计模式下显示为空字符串.在'design-mode'数据上下文类中,我想返回我可能拥有的每个绑定属性的属性名称.

希望这可以解释您的担忧.

Nam*_* VU 10

过了一会儿,我找到了如下的解决方案,这对我来说非常方便.

    string SomeProperty
    {
        get
        {
            return GetDesignModeValue(() => this.SomeProperty);
        }
    }

    string GetDesignModeValue<T>(Expression<Func<T>> propertyExpression)
    {
        var propName = (propertyExpression.Body as MemberExpression).Member.Name;
        var value = string.Format(
            "<{0}>"
            , propName);
        return value;
    }
Run Code Online (Sandbox Code Playgroud)

因此,从现在开始,mocking在设计模式下显示绑定属性的值要容易得多.

我希望有一天你会觉得它很有帮助!

  • 使用Visual Studio 2015时,您只需使用operator关键字[nameof(this.SomeProperty)](https://msdn.microsoft.com/en-us/library/dn986596.aspx) (2认同)