问题描述
我只是想确认我所理解的关于泛型在C#。这已经出现在一对夫妇的代码库,我在一个通用的基类,用于创建类型安全的衍生的实例工作。一个非常简单的例子,我在说一下,
I just want to confirm what I've understood about Generics in C#. This has come up in a couple code bases I've worked in where a generic base class is used to create type-safe derived instances. A very simple example of what I'm talking about,
public class SomeClass<T>
{
public virtual void SomeMethod(){ }
}
public class DeriveFrom :SomeClass<string>
{
public override void SomeMethod()
{
base.SomeMethod();
}
}
,问题出现了,当我再要使用派生在一个多态的方式实例。
The problem comes up when I then want to use derived instances in a polymorphic way.
public class ClientCode
{
public void DoSomethingClienty()
{
Factory factory = new Factory();
//Doesn't compile because SomeClass needs a type parameter!
SomeClass someInstance = factory.Create();
someInstance.SomeMethod();
}
}
看来,一旦你介绍一个通用成一个继承层次结构或接口,可以不再使用家庭类多态的方式也许除了内部本身。是真的吗?
It seems that once you introduce a Generic into an inheritance hierarchy or interface, you can no longer use that family of classes in a polymorphic way except perhaps internal to itself. Is that true?
推荐答案
据我所看到的,耗时的代码不需要泛型类的细节(也就是说,它不取决于什么 T
是)。那么,你为什么不引入接口 SomeClass的< T>
将实施,并使用这个接口的实例
As far as I can see, consuming code doesn't need specifics of generic class (i.e., it doesn't depends on what T
is). So, why don't you introduce interface that SomeClass<T>
will implement, and use instance of this interface.
例如:
public interface ISome
{
void SomeMethod();
}
public class SomeClass<T>: ISome
{
public virtual void SomeMethod(){ }
}
public void DoSomethingClienty()
{
Factory factory = new Factory();
ISome someInstance = factory.Create();
someInstance.SomeMethod();
}
现在,子类 SomeClass的< T>
可以在不同的 T的运作方式不同
S,但消费的代码不会改变。
Now, subclasses of SomeClass<T>
can operate differently on different T
s, but consuming code won't change.
这篇关于C#泛型和多态性:一个矛盾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!