使用字符串常量通知财产变 [英] Using string constant for notify property changed

查看:141
本文介绍了使用字符串常量通知财产变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一些现有的代码工作,并试图找出优势(如果有的话)实现INotifyPropertyChanged接口在使用字符串常量为属性的名称。



因此​​,例如这样做:

  / * 
*为什么要在下面OnPropertyChanged使用,而不是字符串
*?
* /
公共常量字符串CustomerIdPropertyName =客户ID;

私人诠释_customerId;
公众诠释客户ID
{
得到
{
返回_customerId;
}

{
如果(_cusomterId =价值!)
{
_customerId =价值;
OnPropertyChanged(CustomerIdPropertyName);
}
}
}



而不是这样的:

 私人诠释_customerId; 
公众诠释客户ID
{
得到
{
返回_customerId;
}

{
如果(_cusomterId =价值!)
{
_customerId =价值;
OnPropertyChanged(客户编号);
}
}
}


解决方案

这两个版本都同样容易出现输入错误



如果你有几分最近的.NET版本,你的财产变处理函数应该是这样的:

 受保护的虚拟无效OnPropertyChanged([CallerMemberName]字符串参数propertyName = NULL)
{
VAR处理器= this.PropertyChanged ;
如果(处理!= NULL)
{
处理器(这一点,新PropertyChangedEventArgs(propertyName的));
}
}



那么你的财产是这样的:

 私人诠释_customerId; 
公众诠释客户ID
{
得到
{
返回_customerId;
}

{
如果(_cusomterId =价值!)
{
_customerId =价值;
this.OnPropertyChanged();
}
}
}

和你没有与打字错误任何麻烦。


I am working with some existing code and trying to figure out the advantage (if any) of using a string constant for the name of a property when implementing INotifyPropertyChanged interface.

So for example doing this:

/*
 * Why use this instead of string literal
 * in OnPropertyChanged below??
 */
public const string CustomerIdPropertyName = "CustomerId";

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              OnPropertyChanged(CustomerIdPropertyName);
         }
    }
}

Instead of this:

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              OnPropertyChanged("CustomerId");
         }
    }
}

解决方案

Both versions are equally prone to typing errors.

If you have a somewhat recent version of .NET, your property changed handler should look like this:

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
  var handler = this.PropertyChanged;
  if (handler != null)
  {
    handler(this, new PropertyChangedEventArgs(propertyName));
  }
}

Then your property looks like this:

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              this.OnPropertyChanged();
         }
    }
}

And you don't have any trouble with typing errors.

这篇关于使用字符串常量通知财产变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆