[英]Get property name in the property's Set{} method
In C# 4.0 I am doing the following: 在C#4.0中,我正在执行以下操作:
public string PropertyA
{
get;
set
{
DoSomething("PropertyA");
}
}
public string PropertyB
{
get;
set
{
DoSomething("PropertyB");
}
}
..I have a lot of these properties and doing it manually will be a pain. ..我有很多这些属性,手动执行将很痛苦。 Is there a way I could replace this with: 有没有一种方法可以替换为:
public string PropertyA
{
get;
set
{
DoSomething(GetNameOfProperty());
}
}
..maybe using reflection? ..也许使用反射?
In .NET 4.5 your DoSomething
method should use the [CallerMemberName]
parameter attribute: 在.NET 4.5中,您的DoSomething
方法应使用[CallerMemberName]
参数属性:
void DoSomething([CallerMemberName] string memberName = "")
{
// memberName will be PropertyB
}
Then just call it like this: 然后像这样调用它:
public string PropertyA
{
get
{
...
}
set
{
DoSomething();
}
}
There is no way to do this in current C# versions, reflection won't help. 在当前的C#版本中无法执行此操作,反射将无济于事。 You could hack this with expressions and get compile time checking, but that's about it, you'd have to type even more code too 您可以使用表达式破解并获得编译时间检查,仅此而已,您还必须输入更多代码
DoSomething(()=>this.PropertyA); // have dosomething take an expression and parse that to find the member access expression, you'll get the name there
A good alternative if that's possible for you would be to use Postsharp to do this instead in a clean way, but that may not always be possible. 如果可能的话,一个不错的选择是使用Postsharp以一种干净的方式进行此操作,但这并非总是可能的。
You can use reflection of GetCurrentMethod
. 您可以使用GetCurrentMethod
反射。
public string PropertyA
{
get;
set
{
DoSomething(MethodBase.GetCurrentMethod().Name.Substring(4));
}
}
It's available for .Net 4. 它适用于.Net 4。
As @hvd explains, the Name will return set_PropertyA
, then use Substring
to take the property name. 正如@hvd解释的那样,Name将返回set_PropertyA
,然后使用Substring
来获取属性名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.