使用元数据来获取对调用某个方法的类的引用

时间:2014-06-19 04:24:49

标签: c#

使用INotifyPropertyChanged时,可以执行类似这样的操作来获取调用调用事件的方法的属性的名称。

 public void RaisePropertyChanged([CallerMemberName] string prop = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(new object(), new PropertyChangedEventArgs(prop));

        }

    }

是否还有其他类型的属性用于获取对包含该属性的类的引用?我希望能够从任何viewmodel类的任何属性中调用RaisePropertyChanged()。我的所有viewmodel类都来自一个基础,所以我认为我可以做这样的事情。

 public void RaisePropertyChanged([CallerMemberName] string prop = "", [CallerClassRef] VmBase base = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(base, new PropertyChangedEventArgs(prop));

        }

    }

2 个答案:

答案 0 :(得分:0)

尝试使用Fody - PropertyChanged添加。它可以帮助您将INotifyPropertyChanged实现注入IL代码。

源代码:

[ImplementPropertyChanged]
public class Person 
{        
    public string GivenNames { get; set; }
    public string FamilyName { get; set; }

    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", GivenNames, FamilyName);
        }
    }
}

编译时

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    string givenNames;
    public string GivenNames
    {
        get { return givenNames; }
        set
        {
            if (value != givenNames)
            {
                givenNames = value;
                OnPropertyChanged("GivenNames");
                OnPropertyChanged("FullName");
            }
        }
    }

    string familyName;
    public string FamilyName
    {
        get { return familyName; }
        set 
        {
            if (value != familyName)
            {
                familyName = value;
                OnPropertyChanged("FamilyName");
                OnPropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", GivenNames, FamilyName);
        }
    }

    public virtual void OnPropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

源代码复制自:https://github.com/Fody/PropertyChanged

答案 1 :(得分:0)

访问当前类引用的关键字称为this

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

无论你派生这个类多少次,这都会有效,this总是调用这个函数的实例。