【问题标题】:Get property name in the property's Set{} method在属性的 Set{} 方法中获取属性名称
【发布时间】:2014-10-27 22:17:22
【问题描述】:

在 C# 4.0 中,我正在执行以下操作:

public string PropertyA
{
  get;
  set
  {
    DoSomething("PropertyA");
  }
}

public string PropertyB
{
  get;
  set
  {
    DoSomething("PropertyB");
  }
}

..我有很多这些属性,手动操作会很痛苦。有没有办法可以将其替换为:

public string PropertyA
{
  get;
  set
  {
    DoSomething(GetNameOfProperty());
  }
}

..也许使用反射?

【问题讨论】:

  • 它现在没有多大帮助,但 C# 6 将具有 nameof 运算符,它将执行与您正在寻找的类似的操作,并进行编译时检查。 (假设您仍然需要在任何地方写两次属性名称,但编译器会告诉您是否拼错了。)
  • 听起来像是 XY 问题 - 你这样做是为了解决什么问题?
  • @Sayse 对我来说听起来不像。这是实现INotifyPropertyChanged 的常见模式。
  • @hvd - 非常正确,我已经有一段时间没有实现它了
  • 如果您的目标是 .NET Framework 4.5,您可以使用 CallerMemberNameAttribute

标签: c# .net reflection


【解决方案1】:

你可以使用GetCurrentMethod的反射。

public string PropertyA
{
    get;
    set
    {
        DoSomething(MethodBase.GetCurrentMethod().Name.Substring(4));
    }
}

它适用于 .Net 4。

正如@hvd 所解释的,名称将返回set_PropertyA,然后使用Substring 获取属性名称。

【讨论】:

  • @Sayse 当前方法将是属性设置器,名为set_PropertyA。这也解释了.Substring(4)。
  • @John,这是您要寻找的反射吗?
【解决方案2】:

在当前的 C# 版本中无法做到这一点,反射也无济于事。你可以用表达式破解它并获得编译时间检查,但仅此而已,你还必须输入更多代码

 DoSomething(()=>this.PropertyA); // have dosomething take an expression and parse that to find the member access expression, you'll get the name there

如果可能的话,一个不错的选择是使用 Postsharp 以一种干净的方式执行此操作,但这可能并不总是可行。

【讨论】:

    【解决方案3】:

    在 .NET 4.5 中,您的 DoSomething 方法应使用 [CallerMemberName] 参数属性:

    void DoSomething([CallerMemberName] string memberName = "")
    {
        // memberName will be PropertyB
    }
    

    那就这样称呼它吧:

    public string PropertyA
    {
         get
         {
             ...
         }
         set
         {
             DoSomething();
         }
    }
    

    请参阅MSDN。

    【讨论】:

    • CallerMemberNameAttribute 在 C# 4.0 中不可用。
    • 这在.Net 4.0中是否也存在
    • 它适用于 .NET 4.0,前提是您定义自己的 CallerMemberNameAttribute 类型并使用 C# 5.0 编译器。只是在 C# 4.0 中不起作用。
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2021-12-04
    • 2014-06-27
    • 2010-11-05
    相关资源
    最近更新 更多