如何将事件添加到已定义的属性? [英] How to add an event to a defined property?

查看:81
本文介绍了如何将事件添加到已定义的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我不是C#专业人士,所以有时我会遇到这样的问题:
我可以使用 get {}定义一个包含属性的对象; set {} ,如何为该对象定义一个事件? (如OnChange事件)

谢谢.

Hi people, I''m not professional in C#, so sometimes I face some probs like this:
I can define an object containing properties using get{ }; set{ }, how can I define an event to this object? (like OnChange event)

Thanks.

推荐答案

正如克里斯蒂安所说,如果您想在设置器中进行任何验证或事件引发,则不能使用自动属性.

要自己做并引发一个事件,这是基本模式:
As Christian said, you can''t use auto properties if you want to do any validation or event raising in the setter.

To do it yourself and raise an event, this is the basic pattern:
using System;

public class SampleClass
{
    public event EventHandler ValueChanged;

    private int value;

    public int Value
    {
        get { return value; }
        set
        {
            if (this.value != value)
            {
                this.value = value;
                OnValueChanged(EventArgs.Empty);
            }
        }
    }

    protected virtual void OnValueChanged(EventArgs e)
    {
        EventHandler eh = ValueChanged;
        if (eh != null)
            eh(this, e);
    }
}


您不需要使用您演示的自动生成的内容,而是定义一个在属性中显式获取和设置的私有成员.然后,您还可以定义一个事件并在设置器中触发它(我假设).
You need to not use the auto generated stuff you illustrated, but define a private member that is explicity get and set in your property. Then you can also define an event and fire it within your setter ( I assume ).


好,这是一个完整的解决方案,大致与通常推荐的最佳做法相对应...我建议您阅读了有关代表和事件基础的文章,这对您有很大帮助.

Ok, here is a complete solution which roughly corresponds to commonly recommended best practices... I suggest that you read an article about the basics of delegates and events, that will help you a lot.

class MyClass {
  private string someValue; // Backing field

  public string SomeValue {
    get { return someValue; }
    set {
      // The event only needs to be raised when the value actually changes
      if (value == someValue) return;
      someValue = value;
      OnSomeValueChanged();
    }
  }

  public event EventHandler SomeValueChanged;

  private void OnSomeValueChanged() {
    // This is the simplest way to raise the event (and it is NOT thread safe)
    if (SomeValueChanged != null) SomeValueChanged(this, EventArgs.Empty);
  }
}



您可能想使用与EventHandler不同的委托类型,并创建一个自定义的EventArgs类...我给您的示例只是一个开始.



You may want to use a different delegate type than EventHandler and create a custom EventArgs class... The example I gave you is just a start.


这篇关于如何将事件添加到已定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆