C# 泛型和多态性:矛盾吗?

C# Generics and polymorphism: an oxymoron?(C# 泛型和多态性:矛盾吗?)
本文介绍了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 Ts, but consuming code won't change.

这篇关于C# 泛型和多态性:矛盾吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)