C# Generics and polymorphism: an oxymoron?(C# 泛型和多态性:矛盾吗?)
问题描述
我只是想确认一下我对 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();
}
}
似乎一旦将 Generic 引入继承层次结构或接口,您就不能再以多态方式使用该类族,除非它可能是其内部的.这是真的吗?
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
上进行不同的操作,但使用代码不会改变.
Now, subclasses of SomeClass<T>
can operate differently on different T
s, but consuming code won't change.
这篇关于C# 泛型和多态性:矛盾吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 泛型和多态性:矛盾吗?


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01