0

我正在尝试使用 C# 4.0 开发 Silverlight 4 应用程序。我有一个这样的案例:

public class Foo<T> : IEnumerable<T>
{
    ....
}

别处:

public class MyBaseType : MyInterface
{
    ...
}

以及我遇到问题的用法:

Foo<MyBaseType> aBunchOfStuff = new Foo<MyBaseType>();
Foo<MyInterface> moreGeneralStuff = myListOFStuff;

现在我相信这在 C# 3.0 中是不可能的,因为泛型类型是“不变的”。但是我认为这在 C# 4.0 中通过泛型技术的新协变是可能的?

据我了解,在 C# 4.0 中,许多通用接口(如 IEnumerable)已被修改以支持变化。在这种情况下,我的Foo班级是否需要任何特别的东西才能成为协变的?

Silverlight 4 (RC) 是否支持协方差?

4

2 回答 2

4

要指示接口或委托的泛型类型参数在 中是协变的T,您需要提供out关键字。

然而,目前这对于类是不可能的。我建议创建一个带有协变泛型类型参数的接口,并让你的类实现它。

至于 Silverlight 4 中的协方差支持:在 beta 版本中不支持,我需要检查他们是否在候选版本中实现了它。编辑:显然是这样。

Edit2:由于 BCL 中的某些类型没有设置适当的泛型类型修饰符(IEnumerable<T>, Action<T>, Func<T>, ...) ,SL4 是否真的支持接口和委托的协变和逆变可能会有些混淆.

Silverlight 5 解决了这些问题:http: //10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5

然而,SL4 编译器确实支持inandout修饰符。以下编译并按预期工作:

interface IFoo<out T>
{
    T Bar { get; }
}
interface IBar<in T>
{
    void Add(T value);
}
delegate void ContravariantAction<in T>(T value);
delegate T CovariantFunc<out T>();
于 2010-04-01T06:44:09.343 回答
1

仅接口和委托支持协方差:

public interface Foo<out T> { }
public class Bar<T> : Foo<T> { }

interface MyInterface { }
public class MyBase : MyInterface { }

Foo<MyBase> a = new Bar<MyBase>();
Foo<MyInterface> b = a;

重要的是outInterface 上的 -Keyword Foo

于 2010-04-01T06:41:59.597 回答