gpt4 book ai didi

c# - 是否可以知道对象属性何时更改?

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

每当更改结构或对象属性时,我都需要进行控制。它没有任何我可以使用的事件。

示例:我如何知道宽度或高度何时更改?这可能吗?

“System.Drawing.Size = 尺寸”

    private Size mySize;

public Size MySize
{
get {
//What if X or Y is changed?? I need to know that
return mySize;
}
set {

mySize = value;
}
}

对于这种特定情况,如果 Size 属性是只读的,问题就会得到解决。但他们不是。

最佳答案

根据评论进行编辑:

Sample: How can I know when the Width or Height is changed? Is that even possible?

不,这是不可能的。不过,没关系。

当您从类中返回一个Size 时,因为Size is a struct ,您返回的是一份副本。即使用户更改您返回的 SizeWidthHeight,也不会影响 mySize类中的结构。

为了改变你的尺寸,他们需要改变整个东西,即:

var temp = yourClass.MySize;
temp.Width = newWidth;
yourClass.MySize = temp; // The user will need to assign an entire Size

就您而言,Size 属性实际上是只读的,因为 System.Drawing.Size 是一个值类型。


原始答案,假设宽度和高度是用户类的属性:

主要有两个选项——

您可以根据您的宽度和高度动态计算尺寸,而不是存储它:

public Size MySize
{
get {
return new Size(Width,Height);
}
set {
Width = value.Width;
Height = value.Height; // Set Width/Height appropriately
}
}

另一种选择是在宽度和高度的属性 setter 中重新计算尺寸:

public double Width
{
get { return width; }
set
{
width = value;
mySize = new Size(width, Height); // Compute new size, so it's always correct
}
}

最后,如果您使用 INotifyPropertyChanged 之类的东西来跟踪更改,您还可以订阅自己的 PropertyChanged 事件,如果它是合适的属性,则重新计算您的尺寸。

关于c# - 是否可以知道对象属性何时更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17682183/

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