INotifyPropertyChanged和自动属性

HCL*_*HCL 48 .net c# vb.net

有没有办法使用INotifyPropertyChanged自动属性?也许是一个属性或其他东西,对我来说并不明显.

public string Demo{
    get;set;
}
Run Code Online (Sandbox Code Playgroud)

对我来说,自动属性是一个非常实用的东西,但几乎总是,我必须提高PropertyChanged-event如果属性值已被更改并且没有机制来执行此操作,自动属性对我来说是无用的.

cre*_*7or 13

在.NET 4.5及更高版本中,它可以缩短一些:

private int unitsInStock;
public int UnitsInStock
{
    get { return unitsInStock; }
    set { SetProperty(ref unitsInStock, value);}
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*isF 11

这是你必须自己编码的东西.您可以获得的最接近的类似于Code Project上的此实现,它使用自定义属性和面向方面的方法来提供此语法:

[NotifyPropertyChanged] 
public class AutoWiredSource
{ 
   public double MyProperty { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

有人曾经在Microsoft Connect上提出对C#规范的更改实现了这个:

class Person : INotifyPropertyChanged
{
    // "notify" is a context keyword, same as "get" and "set"
    public string Name { get; set; notify; }
}
Run Code Online (Sandbox Code Playgroud)

但该提案现已结束.


Ada*_*son 9

没有内置的机制来做到这一点.像PostSharp这样的东西可能会为你添加这样的东西(或Mark Gravell的HyperDescriptor,如果你只是想让这个数据绑定感知).

  • 还有Fody.PropertyChanged https://github.com/Fody/PropertyChanged(将引发PropertyChanged事件的代码注入实现INotifyPropertyChanged的类的属性设置器中),这不需要应用任何属性,但也可以删除一些控制过程。 (2认同)