Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - casting delegate

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.

Hope you can help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

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;

... 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...