我有一个具有数十个属性的类需要引发属性更改事件,目前我的代码看起来像
public class Ethernet : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string timeStamp;
public string TimeStamp
{
get { return timeStamp; }
set
{
timeStamp = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("TimeStamp"));
}
}
}
C#中是否有更短的编写此类代码的方法,我正在为每个属性进行过多的复制/粘贴操作,我觉得必须有更好的方法。
答案 0 :(得分:6)
(这是一个较短的评论,但显然我不允许发布一个,但是。默认情况下,请随时将以下内容降级为评论。)
引用的代码不像编写的那样是线程安全的。请参阅Pattern for implementing INotifyPropertyChanged?为什么下面的代码更好,以及在接受的回复中链接到Eric Lippert的博客为什么故事不会在那里结束。
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs("TimeStamp"));
有关实际问题的答案,请参阅Implementing INotifyPropertyChanged - does a better way exist?,包括此C#6.0快捷方式。
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TimeStamp"));
答案 1 :(得分:1)
请看一下这个答案:https://stackoverflow.com/a/2339904/259769
我的代码提供和扩展方法可以替换大部分设置代码,让您将代码缩短为:
public class Ethernet : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string timeStamp;
public string TimeStamp
{
get { return timeStamp; }
set { this.NotifySetProperty(ref timeStamp, value, () => this.TimeStamp); }
}
}
此代码的另一个明显优势是它会立即变为强烈类型的属性名称。
答案 2 :(得分:0)
在MVVM模式中,经常使用属性change / ing,典型的基本解决方案如下:
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChanged([CallerMemberName] string propertyName = null)
{
if (propertyName == null)
throw new ArgumentNullException("propertyName");
try
{
this.OnPropertyChanged(propertyName);
}
catch (Exception exception)
{
Trace.TraceError("{0}.OnPropertyChanged threw {1}: {2}", this.GetType().FullName, exception.GetType().FullName, exception);
}
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Ethernet : ViewModelBase
{
private DataTime timeStamp;
public DateTime TimeStamp
{
get
{
return timeStamp;
}
set
{
timeStamp = value;
FirePropertyChanged();
}
}
}
答案 3 :(得分:0)
我爱上了这堂课:
[Serializable]
public class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(T value, ref T field, Expression<Func<object>> property)
{
return SetProperty(value, ref field, GetPropertyName(property));
}
protected virtual bool SetProperty<T>(T value, ref T field, [CallerMemberName] string propertyName = null)
{
if (field == null || !field.Equals(value))
{
field = value;
OnPropertyChanged(propertyName);
return true;
}
return false;
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void OnPropertyChanged(Expression<Func<object>> property)
{
OnPropertyChanged(GetPropertyName(property));
}
protected string GetPropertyName(Expression<Func<object>> property)
{
var lambda = property as LambdaExpression;
MemberExpression memberExpression;
var unaryExpression = lambda.Body as UnaryExpression;
if (unaryExpression != null)
{
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
{
memberExpression = (MemberExpression) lambda.Body;
}
var propertyInfo = memberExpression?.Member as PropertyInfo;
return propertyInfo?.Name ?? string.Empty;
}
}
这样做的一个巨大优势是它会检查值是否已更改。这将最小化对视图的更新调用。对于您的示例,它看起来像这样:
public class Ethernet : PropertyChangedBase
{
private string _timeStamp;
public string TimeStamp
{
get { return _timeStamp; }
set { SetProperty(value, ref _timeStamp); }
}
}
如果您真的很舒服,可以为此编写代码片段。这将是片段部分:
<Snippet>
<Declarations>
<Literal>
<ID>PropertyName</ID>
<Type>String</Type>
<ToolTip>The property name</ToolTip>
<Default>NewProperty</Default>
</Literal>
<Literal>
<ID>PropertyType</ID>
<Type>
</Type>
<ToolTip>Replace with the type of the property</ToolTip>
<Default>string</Default>
</Literal>
<Object>
<ID>PrivateVariable</ID>
<Type>Object</Type>
<ToolTip>The name of the private variable</ToolTip>
<Default>newPropertyValue</Default>
</Object>
</Declarations>
<Code Language="csharp" Kind="method decl"><![CDATA[ private $PropertyType$ _$PrivateVariable$;
public $PropertyType$ $PropertyName$
{
get { return _$PrivateVariable$; }
set
{
SetProperty(value, ref _$PrivateVariable$);
}
}]]></Code>
</Snippet>