在对象初始值设定项中分配事件

Max*_*Max 21 .net c# events delegates object-initializers

为什么不能在C#中的对象初始值设定项中分配事件和属性?这样做似乎很自然.

var myObject = new MyClass()
     {
        Property = value,
        Event1 = actor,
        // or
        Event2 += actor
     };  
Run Code Online (Sandbox Code Playgroud)

还是有一些我不知道的技巧?

Ani*_*Ani 6

至于外部合同而言,事件没有一个二传手,只addremove 方法 -用户可以注册并从事件注销,并发布对象决定何时通过"提升"事件调用回调.因此,一般来说,"分配事件"的想法毫无意义.

但是,当您在类中声明一个事件时,C#编译器会为您提供真正方便的功能:当您不提供自己的实现时,它会为您创建一个私有的支持委托字段,以及适当的添加/删除实现.这允许您在类中"设置事件"(实际上是支持字段),但不在其外部.要理解这一点,请考虑:

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 };
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这与限制无关.属性具有setter方法和私有支持字段,但对象初始化程序可以正常工作. (7认同)

Dre*_*kes 5

由于最初的问题,这并没有使C#6或C#7成为现实,但是尚未做出决定。GitHub上存在一个跟踪语言建议的问题。您可以在那里投票,也可以通过链接进入有关该功能的先前讨论。

https://github.com/dotnet/csharplang/issues/307

如果您想查看此功能,请竖起大拇指以帮助提高其知名度。

建议的语法为:

var timer = new DispatcherTimer {
    Tick += delegate {},
    Interval = TimeSpan.FromSeconds(1d),
};
Run Code Online (Sandbox Code Playgroud)