gpt4 book ai didi

C# : Creating Events for a Class on GET/SET properties

转载 作者:行者123 更新时间:2023-11-30 19:03:53 25 4
gpt4 key购买 nike

每次我的类中的属性被设置时,我都希望触发一个事件。我希望能够在设置我的其中一个属性时触发相同的事件。我有(大约 12 个)

public class MyClass
{
private int _myHeight;
private int _myWidth;

public int myHeight
{
get { return myHeight; }
set { myHeight = value;
//This fires event!
}
}
public int myWidth
{
get { return myWidth; }
set { myWidth = value;
//This will fire the same event!
}

我对事件本身并不陌生,但对创建事件却很陌生。我一直使用 Windows 应用程序中使用的“开箱即用”事件。有什么想法吗?

最佳答案

使用 INotifyPropertyChange 是正确的方法(因为它是 .NET 中广泛使用的类型,所以任何人都可以理解您的意图)。但是,如果您只想从一些简单的代码开始,那么您的类的实现可能如下所示:

public class MyClass 
{
private int _myHeight;
public event EventHandler Changed;

protected void OnChanged() {
if (Changed != null) Changed(this, EventArgs.Empty);
}

public int myHeight
{
get { return myHeight; }
set {
myHeight = value;
OnChanged();
}
}
// Repeat the same pattern for all other properties
}

这是最直接的代码编写方式(这可能有利于学习,但不利于更大的实际应用程序)。

关于C# : Creating Events for a Class on GET/SET properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2302827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com