简体   繁体   English

通用类的协方差

[英]Covariance for generic classes

Is there any way in C# to achieve the following: C#中有什么方法可以实现以下目的:

class MyClass<T>  where T : BaseTypeInner {}

class BaseTypeInner {}

class A : BaseTypeInner {}

class B : BaseTypeInner {}

void Main()
{
    MyClass<BaseTypeInner> variant;

    variant = new MyClass<A> (); // ERROR: Cannot implicitly convert type 'UserQuery.MyClass<UserQuery.A>' to 'UserQuery.MyClass<UserQuery.BaseTypeInner>'

    variant = new MyClass<B> ();
}

In C# only interfaces can be variant. 在C#中,仅接口可以是变量。 Quoting C# spec: 引用C#规范:

Variant type parameter lists can only occur on interface and delegate types. 变体类型参数列表只能出现在接口和委托类型上。

So you could declare a generic, covariant interface IBaseClass<out T> , make BaseClass<T> implement it, and later on cast to IBaseClass<BaseTypeInner> instead of casting to the class. 因此,您可以声明一个通用的协变接口IBaseClass<out T> ,使BaseClass<T>实现它,然后将其IBaseClass<BaseTypeInner>转换为IBaseClass<BaseTypeInner>而不是强制转换为该类。

interface IMyClass<out T> where T : BaseTypeInner { }

class MyClass<T> : IMyClass<T> where T : BaseTypeInner { }
IMyClass<BaseTypeInner> variant;

variant = new MyClass<A>(); // works just fine
variant = new MyClass<B>();

A possible solution is to have a base type for the base generic type: 一个可能的解决方案是为基本通用类型具有一个基本类型:

class BaseType {}

class MyClass<T> : BaseType where T : BaseTypeInner {}

class BaseTypeInner {}

class A : BaseTypeInner {}

class B : BaseTypeInner {}

void Main()
{
    BaseType variant;

    variant = new MyClass<A> ();

    variant = new MyClass<B> ();
}

But, that's not a good idea because I'm using a lower class that's not generic so I'm losing all the details and restrictions I get from using type parameters. 但是,这不是一个好主意,因为我使用的是非通用的较低类,因此我失去了使用类型参数所获得的所有详细信息和限制。

No, however it is possible to provide custom CastUp / CastDown methods to achieve this. 否,但是可以提供自定义的CastUp / CastDown方法来实现此目的。 ImmutableArray<T> , part of the .NET BCL, does this . .NET BCL的一部分ImmutableArray<T> 做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM