在属性的Set {}方法中获取属性名称

时间:2014-09-03 12:07:01

标签: c# .net reflection

在C#4.0中,我正在做以下事情:

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

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

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

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

..也许使用反射?

3 个答案:

答案 0 :(得分:2)

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

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

然后就这样称呼它:

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

请参阅MSDN

答案 1 :(得分:0)

在当前的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以干净的方式执行此操作,那么这是一个不错的选择,但这可能并非总是可行。

答案 2 :(得分:0)

您可以使用GetCurrentMethod的反映。

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

可用于.Net 4。

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

相关问题