本文介绍了你能否用一个特定类型的类来继承一个泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public abstract class GenericBase< T>< p> 
其中T:Interface1
{
}

子类泛型与特定实现:

  public class Customer:
GenericBase< Type1>

Type1 执行 Interface1 )。



我有另一个抽象基类有一个引用:

 受保护的GenericBase< Interface1> genericInstance; 

最后,当我试图将genericInstance赋值给基类的一个实例时,它给了我一个编译器错误,说它不能隐式地将客户转换为GenericBase< Interface1>。
$ b $ pre $ base $ .genericInstance = new Customer() ; //编译错误

我不明白为什么我会得到这个错误if Customer GenericBase< Type1> Type1 implements的子类型接口1 。不是 Customer 有效地是 GenericBase< Interface1> 类型,如果它是的子类, GenericBase< Type1>



我假设我在这里误解了泛型。有没有办法允许这种行为?

解决方案

在C#中,协变(派生类型为基类型)不能应用于泛型类。因此,您需要使用来应用专门标记为协变的接口>在新的 IGenericBase 接口上。

  protected IGenericBase< Interface1> genericInstance = new Customer(); 

public interface IGenericBase< out T> {}

公共抽象类GenericBase< T> :IGenericBase< T>
其中T:接口1 {}

公共接口接口1 {}
$ b公共类类型1:接口1 {}

公共类客户: GenericBase<类型1> {}


I have a generics class with a subclass that provides specific types.

public abstract class GenericBase<T>
    where T:Interface1
{
}

I subclass the generics with specific implementations:

public class Customer:
    GenericBase<Type1>

(Type1 implements Interface1).

I have another abstract base class that has a reference to this:

protected GenericBase<Interface1> genericInstance;

Finally, when I attempt to assign the genericInstance to an instance of the base class, it gives me a compiler error, saying that it "cannot implicitly convert Customer to GenericBase<Interface1>".

base.genericInstance = new Customer(); //Compiler error

I don't understand why I would get this error if Customer is a subtype of GenericBase<Type1>, and Type1 implements Interface1. Isn't Customer effectively a type of GenericBase<Interface1>, if it's a subclass of GenericBase<Type1>?

I assume I'm misunderstanding something about generics here; is there a way to allow this behavior?

解决方案

In C#, covariance (assigning a derived type to a base type) cannot be applied to generic classes. As a result, you would need to apply an interface specifically marked as covariant, using the out parameter modifier on a new IGenericBase interface.

protected IGenericBase<Interface1> genericInstance = new Customer();

public interface IGenericBase<out T> {}

public abstract class GenericBase<T> : IGenericBase<T>
    where T:Interface1 {}

public interface Interface1 {}

public class Type1 : Interface1 {}

public class Customer: GenericBase<Type1> {}

这篇关于你能否用一个特定类型的类来继承一个泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:16