传递枚举元素作为事件参数C# [英] Pass enum elements as event args C#

查看:155
本文介绍了传递枚举元素作为事件参数C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将枚举元素作为事件参数传递吗?

Is it possible to pass Enum elements as event arguments ?

让我们说我有..

public class Letters
{
    public delegate void StateChangedEventHandler(object sender, EventArgs e);
    public event StateChangedEventHandler StateChanged;

    public AbcState state = AbcState.Aaa;     
    public AbcState State
    {
        get{return this.state;}
        set
        {
            this.state = value;
            this.OnStateChanged();
        }
    }

    public enum AbcState
    {
        Aaa,
        Bbb,
        Ccc
    }

    protected virtual void OnStateChanged()
    {
        StateChanged?.Invoke(this, State);
    }

看到我如何将枚举的元素作为事件参数传递?
现在,我通常会创建一个类并扩展EventArgs,然后我可以传递类本身。
我知道我可以这样做,创建一个不同的类扩展EventArgs,然后在类中创建枚举,字段和属性。然后将后一个实例放入我的类Letters(用于上面的代码)。

See how I am trying to pass the element of the enum as an event argument? Now, I normally would create a class and extends EventArgs, and then I would be able to pass the class itself. And I know I could do the same here, Create a different class extending EventArgs and then create the enum, field and property right in the class. And then make an instance of the latter into my class "Letters" (used in code above).

但是,是不是疯了?必须有一个更好的方法。请告诉我有一个更简单的方法。

But, isnt that crazy ? There has to be a better way. Please tell me there is a simplier way.

顺便说一句,我不知道上面的代码是否编译,我只是在编辑器中直接写入,因为我不在我的开发电脑现在。

By the way I do not know if the code above would compile I just wrote it straight in the Editor as I am not on my dev computer right now.

推荐答案

如果您希望事件的参数是枚举,那么请确保在声明事件:

If you want the parameter of the event to be the enum, then sure, just specify that as the signature when declaring the event:

public class Letters
{
    public event Action<AbcState> StateChanged;

    private AbcState state = AbcState.Aaa;     
    public AbcState State
    {
        get{return this.state;}
        set
        {
            this.state = value;
            this.OnStateChanged();
        }
    }

    public enum AbcState
    {
        Aaa,
        Bbb,
        Ccc
    }

    protected virtual void OnStateChanged()
    {
        StateChanged?.Invoke(State);
    }
}

这篇关于传递枚举元素作为事件参数C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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