gpt4 book ai didi

c# - 更改静态 int 变量时触发事件?

转载 作者:太空狗 更新时间:2023-10-30 00:55:56 26 4
gpt4 key购买 nike

我现在正在用 Silverlight 5 编写一个网站。我设置了一个 public static 类,在那个类中我定义了一个 public static int。在 MainPage 类(这是一个公共(public)部分类)中,我想在 public static int 更改时捕获一个事件。有什么方法可以设置一个事件来为我执行此操作,还是有另一种方法可以让我获得相同的行为? (或者我正在尝试做的事情是可能的吗?)

最佳答案

为了详细说明 Hans 所说的,您可以使用属性而不是字段

字段:

public static class Foo {
public static int Bar = 5;
}

属性:

public static class Foo {
private static int bar = 5;
public static int Bar {
get {
return bar;
}
set {
bar = value;
//callback here
}
}
}

像使用常规字段一样使用属性。在对它们进行编码时,value 关键字会自动传递给 set 访问器,并且是变量设置的值。例如,

Foo.Bar = 100

将超过 100,因此 value 将为 100

属性本身不存储值,除非它们是自动实现的,在这种情况下,您将无法为访问器(get 和 set)定义主体。这就是我们使用私有(private)变量 bar 来存储实际整数值的原因。

编辑:其实msdn有一个更好的例子:

using System.ComponentModel;

namespace SDKSample
{
// This class implements INotifyPropertyChanged
// to support one-way and two-way bindings
// (such that the UI element updates when the source
// has been changed dynamically)
public class Person : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;

public Person()
{
}

public Person(string value)
{
this.name = value;
}

public string PersonName
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("PersonName");
}
}

// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}

http://msdn.microsoft.com/en-us/library/ms743695.aspx

关于c# - 更改静态 int 变量时触发事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8964377/

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