Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在属性中获取属性名称';s集{}方法_C#_.net_Reflection - Fatal编程技术网

C# 在属性中获取属性名称';s集{}方法

C# 在属性中获取属性名称';s集{}方法,c#,.net,reflection,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

在C#4.0中,我做了以下工作:

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

public string PropertyB
{
  get;
  set
  {
    DoSomething("PropertyB");
  }
}
…我有很多这样的属性,手动操作会很痛苦。有没有一种方法可以替换为:

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

…可能使用反射?

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

void DoSomething([CallerMemberName] string memberName = "")
{
    // memberName will be PropertyB
}
那么就这样称呼它:

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

请参见此部分。

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

您可以使用反射

它适用于.NET4


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

现在没有多大帮助,但C#6将具有一个
nameof
操作符,它将执行与您正在寻找的类似的操作,并带有编译时检查。(假设,你仍然需要在任何地方写两次属性名,但编译器会告诉你是否在某个地方拼写错误。)听起来像是XY问题-你想通过这样做解决什么问题?@Sayse对我来说听起来不像。这是实现
INotifyPropertyChanged
@hvd的一种常见模式-非常正确,自从我实现以来已经有一段时间了,如果您的目标是.NET Framework 4.5,您可以使用
CallerMemberNameAttribute
在C#4.0中不可用。这是否也存在于.NET 4.0中?它可以用于.NET 4.0,如果您定义自己的
CallerMemberNameAttribute
类型并使用C#5.0编译器。只是在C#4.0中它不起作用。@说当前的方法将是属性设置程序,名为
set\u PropertyA
。这也解释了
.Substring(4)
@John,这就是你要寻找的反射吗?
public string PropertyA
{
    get;
    set
    {
        DoSomething(MethodBase.GetCurrentMethod().Name.Substring(4));
    }
}