3

是否可以从其访问器中获取属性的唯一标识符?

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;
        ...
4

1 回答 1

2

你可以使用反射:

[MethodImpl(MethodImplOptions.NoInlining)]
set
{
    string name = MethodBase.GetCurrentMethod().Name;
    // TODO: strip the set_ prefix from the name
}

正如评论部分所指出的,setter 可以内联,因此必须用[MethodImpl]属性修饰它以防止 JITer 这样做。

此外,您必须set_从方法名称中去除前缀​​,因为 name 将等于set_Bar

所以:

string name = MethodBase.GetCurrentMethod().Name.Substring(4);
于 2012-05-02T09:25:25.513 回答