铸造委托 [英] casting delegate

查看:104
本文介绍了铸造委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C#,所以我的问题可能很简单,但在这里不用。

I'm pretty new to c#, so my question might be simple, but here goes.

我一直在试图与代表工作,并。还挺坚持这个问题。

I've have been trying to work with delegates, and is kinda stuck with this problem.

.....
    public delegate double delegateA();
    public delegate double delegateB();

    public static double myFunc()
    {
        return 0;
    }
    public static delegateA myTest()
    {
        return myFunc;
    }

    static void Main(string[] args)
    {
        delegateB myFuncDelegate;

        myFuncDelegate = myTest();  // <-- Error: Cannot implicitly convert type....
    }
.....

我不知道如何使这项转换工作,除非使用相同的委托类型。
,而在我的项目,这将是对委托的是不同的名字更漂亮(因为他们在不同的班级存在。

I don't know how to make this conversion work, unless using the same delegate as type. But in my project, it would be more pretty for the delegate's to have different names (as they exist in different classes.

希望你能帮助我。

推荐答案

您不能代表之间转换,这样直接。您的能有什么的做的是使一个的新的的从现有的,兼容的一名代表因此,如果你改变你的代码:

You can't convert between delegates like that directly. What you can do is make a new delegate from an existing, compatible one. So if you change your code to:

 delegateB myFuncDelegate = new delegateB(myTest());

这将工作(注意,兼容没有按' ŧ必然意味着该签名是相同的 - 详见语言规范)

that will work. (Note that "compatibility" doesn't necessarily meant that the signatures are identical - see the language specification for details.)

只是为了让这个稍微更清楚其他读者,这里有一个简单的完整的例子,它没有按。'吨需要任何方法调用

Just to make this slightly clearer to other readers, here's a simpler complete example, which doesn't need any method calls.

// Two delegate types with the same signature
delegate void Foo();
delegate void Bar();

class Test
{
    static void Main()
    {
        // Actual value is irrelevant here
        Foo foo = null;

        // Error: can't convert like this
        // Bar bar = foo;

        // This works fine
        Bar bar = new Bar(foo);
    }
}

请注意,有一个例外,就是这种无转换规则 - 在C#4例如通用的差异,在C#4你​​的可以的写:

Note that there's one exception to this "no conversions" rule - generic variance in C# 4. For example, in C# 4 you can write:

 Action<object> foo = x => Console.WriteLine(x.GetHashCode());
 Action<string> bar = foo;



...因为动作< T> 逆变 T (所以它实际上被声明为动作<在T> )。这是一个的引用转换的 - 如第一个样品做它不会创建的新的的委托。然而,这不适用于仅是兼容的代表 - 只有那些通用

... because Action<T> is contravariant in T (so it's actually declared as Action<in T>). This is a reference conversion - it doesn't create a new delegate like the first sample does. However, this isn't available for merely "compatible" delegates - only generic ones.

这篇关于铸造委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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