Bra*_*ann 10 .net c# automatic-properties inotifypropertychanged .net-3.5
实现INotifyPropertyChanged接口时,每次在类中更新属性时,您都要负责调用PropertyChanged事件.
这通常会导致以下代码:
public class MyClass: INotifyPropertyChanged
private bool myfield;
public bool MyField
{
get { return myfield; }
set
{
if (myfield == value)
return;
myfield = value;
OnPropertyChanged(new PropertyChangedEventArgs("MyField"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
h(this, e);
}
}
Run Code Online (Sandbox Code Playgroud)
这是每个属性12行.
如果一个人能够装饰这样的自动属性会简单得多:
[INotifyProperty]
public double MyField{ get; set; }
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这是不可能的(例如,请参阅msdn上的这篇文章)
如何减少每个属性所需的代码量?
实际上,每个属性只有3-4行; 其他行在所有"通知"属性上摊销:
class Person : INotifyPropertyChanged
{
#region INotifyPropertyChanged: Shared bit
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
#endregion
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName == value)
return;
_firstName = value;
OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
// Ditto for other properties
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试类似下面的东西,它分享更多的负载:
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { SetNotifyingProperty("FirstName", ref _firstName, value); }
}
private void SetNotifyingProperty<T>(string propertyName,
ref T field, T value)
{
if (value.Equals(field))
return;
field = value;
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
Run Code Online (Sandbox Code Playgroud)
我现在要做的就是在课堂上写下这个:
//AUTOGENERATE INotifyProperty
private bool myfield;
Run Code Online (Sandbox Code Playgroud)
我编写了一个小工具,可以在部分类中生成所有需要的属性代码。这绝不是一个优雅的解决方案,但它确实有效:)
归档时间: |
|
查看次数: |
8193 次 |
最近记录: |