简体   繁体   English

这两种notifyproperty方法之间有什么区别?

[英]What is the difference between these two notifyproperty methods?

Is one better than the other? 这个比那个好吗? Are there any notifyproperty that is best practice? 是否有任何最佳实践的通知属性?

Method 1: 方法1:

 protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

Method 2: 方法2:

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

I'm mainly confused about the "([CallerMemberName] " in the second method, I'm not sure what it does, I think it add an empty string to calls without a string/null, so should I mainly use the second one as it has more broad use? 我主要对第二种方法中的“([[CallerMemberName]””感到困惑,我不确定它的作用,我认为它会在没有字符串/ null的调用中添加一个空字符串,因此我应该主要使用第二种方法因为它有更广泛的用途?

If an optional string parameter is marked [CallerMemberName] , the compiler provides the calling member's name. 如果将可选的string参数标记为[CallerMemberName] ,则编译器将提供调用成员的名称。 So: 所以:

public string Foo {
    get { ... }
    set { ...; OnPropertyChanged(); }
}

automatically provides the "Foo" , saving you some minor inconvenience of explicitly specifying the member name. 自动提供"Foo" ,从而为您明确指定成员名称带来了一些麻烦。

From the documentation . 文档中

You can use the CallerMemberName attribute to avoid specifying the member name as a String argument to the called method. 您可以使用CallerMemberName属性来避免将成员名称指定为被调用方法的String参数。 By using this technique, you avoid the problem that Rename Refactoring doesn't change the String values. 通过使用此技术,可以避免重命名重构不会更改String值的问题。 This is especially useful for the following tasks: 这对于以下任务特别有用:

  • Using tracing and diagnostic routines. 使用跟踪和诊断例程。
  • Implementing the INotifyPropertyChanged interface when binding data. 绑定数据时实现INotifyPropertyChanged接口。 This interface allows the property of an object to notify a bound control that the property has changed, so that the control can display the updated information. 此接口允许对象的属性通知绑定控件该属性已更改,以便控件可以显示更新的信息。 Without the CallerMemberName attribute, you must specify the property name as a literal. 如果没有CallerMemberName属性,则必须将属性名称指定为文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM