开发者

Having trouble assigning to a generic delegate in C#

My problem is as follows:

public abstract class A {}

public class B : A {
    public static IList<B> MyMethod(){ ret开发者_如何学运维urn new List<B>();}
}

public delegate IList<T> MyDelegate<T>() where T : A;



...

public static void CalledMethod<T>() where T : A{
    MyDelegate<T> del = B.MyMethod;  // This doesn't work
}

Can anyone explain the best way to get this to work?

Thanks for any help.

edited to fix example.


Here's why this will not work

public class C: A {}

CalledMethod<C>();

This means that del will be of type MyDelegate<C> which does not work with B.MyMethod because C is not a B.


You need to tell the compiler what MyMethod is:

MyDelegate<T> del = B.MyMethod;


This can't be done the way you are coding it, because you are attempting to make MyDelegate co-variant, but the IList<T> interface returned does not support variance because it can't.

IList<B> and IList<A> can't support variance either way. Think of it this way, a List<SalariedEmployee> can't be completely treated like a List<Employee> since that would let you Add(new HourlyEmployee) incorrectly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜