是否可以从其访问器中获取属性的唯一标识符?
class Foo
{
int Bar
{
set
{
string nameOfThisProperty = X; // where X == "Bar" or any unique value
}
}
}
如果是,怎么做到的?
更新:
我问的原因是:我想要一些一致的唯一值来标识代码正在执行的属性,以避免像我现在正在做的那样必须自己声明一个:
Dictionary<string, RelayCommand> _relayCommands
= new Dictionary<string, RelayCommand>();
public ICommand SomeCmd
{
get
{
string commandName = "SomeCmd";
RelayCommand command;
if (_relayCommands.TryGetValue(commandName, out command))
return command;
...
最佳答案
你可以使用反射:
[MethodImpl(MethodImplOptions.NoInlining)]
set
{
string name = MethodBase.GetCurrentMethod().Name;
// TODO: strip the set_ prefix from the name
}
正如评论部分所指出的,setter 可以被内联,因此必须使用 [MethodImpl]
属性对其进行修饰,以防止 JITer 这样做。
此外,您还必须从方法名称中删除 set_
前缀,因为名称将等于 set_Bar
。
所以:
string name = MethodBase.GetCurrentMethod().Name.Substring(4);
关于c# - 如何从其访问器中获取属性的唯一标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10410925/