为什么使用Delegate.Combine需要强制,但使用+运算符不? [英] Why does using Delegate.Combine require a cast but using the + operator doesn't?

查看:1516
本文介绍了为什么使用Delegate.Combine需要强制,但使用+运算符不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到在反射器+操作下代表 MulticastDelegate

I couldn't find the + operator in Reflector under Delegate or MulticastDelegate.

我试图找出如何,这并不需要一个转换:

I'm trying to figure out how this doesn't need a cast:

Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");

Action c = a + b;



但这:

But this does:

Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");

Action c = (Action)MulticastDelegate.Combine(a, b);

在第一个样品只是在幕后做演员?

In the first sample is the cast just done under the covers?

推荐答案

考虑下面的例子:

class Program
{
    static void Main(string[] args)
    {
        Test1();
        Test2();
    }

    public static void Test1()
    {
        Action a = () => Console.WriteLine("A");
        Action b = () => Console.WriteLine("B");

        Action c = a + b;
        c();
    }

    public static void Test2()
    {
        Action a = () => Console.WriteLine("A");
        Action b = () => Console.WriteLine("B");

        Action c = (Action)MulticastDelegate.Combine(a, b);
        c();
    }
}



然后用ILSpy看着它:

Then looking at it with ILSpy:

internal class Program
{
    private static void Main(string[] args)
    {
        Program.Test1();
        Program.Test2();
    }
    public static void Test1()
    {
        Action a = delegate
        {
            Console.WriteLine("A");
        };
        Action b = delegate
        {
            Console.WriteLine("B");
        };
        Action c = (Action)Delegate.Combine(a, b);
        c();
    }
    public static void Test2()
    {
        Action a = delegate
        {
            Console.WriteLine("A");
        };
        Action b = delegate
        {
            Console.WriteLine("B");
        };
        Action c = (Action)Delegate.Combine(a, b);
        c();
    }
}



似乎他们做同样的事情,只是C#是提供在第一次测试的一些语法糖。

Seems that they do the exact same thing, just C# is providing some syntactic sugar in the first test.

这篇关于为什么使用Delegate.Combine需要强制,但使用+运算符不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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