在对象初始化分配事件 [英] Assigning events in object initializer

查看:163
本文介绍了在对象初始化分配事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能够随着C#中的对象初始化属性分配事件?它似乎是这样自然这样做。

Why isn't it possible to assign events along with properties in object initializers in C#? It seems to be so natural to do so.

var myObject = new MyClass()
     {
        Property = value,
        Event1 = actor,
        // or
        Event2 += actor
     };  

或者是有一些诀窍,我不知道?

Or is there some trick that I don't know of?

推荐答案

据外合同而言,事件没有一个二传手,只添加删除方法的 - 用户可以注册并从事件中注销,而发布的对象,决定何时通过调用回调饲养的事件。因此,分配一个事件,在一般情况下,这个想法是毫无意义的。

As far the external contract is concerned, an event doesn't have a setter, only add and remove methods - subscribers can register and unregister from the event, and the publishing object decides when to invoke the callbacks by 'raising' the event. Consequently, the idea of "assigning an event", in general, is meaningless.

不过,当你在一个类中声明的情况下,C#编译器为您提供了什么是真正的一个方便的特征:当你不提供自己的实现,它创建一个私人的,支持委托场的你,以及相应的添加/删除的实现。这可以让你设置事件类中(实际上是支持字段),而不是外部。要理解这一点,考虑:

However, when you declare an event in a class, the C# compiler provides you with what is really a convenience-feature: when you don't provide your own implementation, it creates a private, backing delegate-field for you, along with the appropriate add / remove implementations . This allows you to "set the event" (really the backing field) within the class, but not outside it. To understand this, consider:

public class Foo
{
    // implemented by compiler
    public event EventHandler MyEvent;

    public static Foo FooFactory(EventHandler myEventDefault)
    {
       // setting the "event" : perfectly legal
       return new Foo { MyEvent = myEventDefault }; 
    }
}

public class Bar
{
    public static Foo FooFactory(EventHandler myEventDefault)
    {
        // meaningless: won't compile
        return new Foo { MyEvent = myEventDefault };
    }
}


public class Baz
{
    // custom implementation
    public event EventHandler MyEvent
    {      
        add { }  // you can imagine some complex implementation here
        remove { } // and here
    }

    public static Baz BazFactory(EventHandler myEventDefault)
    {
        // also meaningless: won't compile
        return new Baz { MyEvent = myEventDefault };
    }
}

这篇关于在对象初始化分配事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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