1

获取方法调用者非常简单,甚至可以使用编译器服务更改属性名称,如下所示:

public class EmployeeVM:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string propertyName=null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            // The compiler converts the above line to:
            // RaisePropertyChanged ("Name");
        }
    }

    private string _phone;

    public string Phone
    {
        get { return _phone; }
        set
        {
            _phone = value;
            OnPropertyChanged();
        // The compiler converts the above line to:
            // RaisePropertyChanged ("Phone");
        }
    }
} 

但是是否有可能从集合本身中获取“集合”函数的调用者?我不知道您如何在该范围内从语法上定义它。AKA,谁在打电话给 Phone= ?

4

2 回答 2

2

查看StackFrame,特别是GetMethod,它为您提供方法名称(您需要选择以前的堆栈帧之一,具体取决于是否编写辅助函数来执行此操作)。文章示例:

            StackTrace st = new StackTrace();
            StackTrace st1 = new StackTrace(new StackFrame(true));
            Console.WriteLine(" Stack trace for Main: {0}",
               st1.ToString());
            Console.WriteLine(st.ToString());

通过搜索 StackFrame 可以找到其他类似的问题,例如How do I find the type of the object instance of the caller of current function?

于 2013-08-06T22:55:31.500 回答
1

不幸的是[CallerMemberName]AttributeUsage 设置为AttributeTargets.Parameter,所以它只能用于参数,就像在方法签名中一样

但是你可以StackFrameAlexei Levenkov提到的那样使用

public string Phone
{
    get { return _phone; }
    set
    {
         string setterCallerName = new StackFrame(1).GetMethod().Name;

        _phone = value;
        OnPropertyChanged();
    }
}
于 2013-08-06T23:09:54.260 回答