代表的Typecast

时间:2017-11-24 09:18:46

标签: c# delegates

我创建了具有相同签名的委托,例如为Thread类job传递的函数:

    public delegate void myDelegateForThread();

    static void Main(string[] args)
    {
        myDelegateForThread del = thrFunc;


        Thread t = new Thread( del);
        t.Start();


        for (int i = 0; i < 10000; i++) { Console.WriteLine("Main thread " +i); }

        Console.ReadLine();

    }

    public static void thrFunc()
    {
        for (int i = 0; i < 10000; i++) { Console.WriteLine("Secondary thread " + i); }
    }

但编译器不满意我没有为ThreadStart构造函数传递Thread。我知道在这种情况下如何解决问题,但我的问题是如果他们有相同的签名,我可以为代表进行类型转换吗?

1 个答案:

答案 0 :(得分:0)

如果您的意思是以下内容,那么它不起作用:

public delegate int MyDelegate1(double param);
public delegate int MyDelegate2(double param);
public int MyFunction(double p) { return 1; }

MyDelegate1 del1 = MyFunction;
MyDelegate2 del2 = (MyDelegate2)del1;

委托与任何其他类型相同,并且没有继承或接口关系 - &gt;即使签名匹配,它们也不能互相转换。

将工作包装在新代理中的工作是什么:

MyDelegate2 del2 = new MyDelegate2(del1);