首页 > 解决方案 > 在 C# 中使用泛型类型

问题描述

我很难弄清楚,如何使用 C# 的通用系统所限制的严格类型系统来实现看似简单的模式。我主要来自 Java 背景,习惯于泛型类型的通配符。由于 C# 不允许这样的事情,我需要你的帮助来找出最优雅的方式来实现以下内容(我的实现是针对 Unity3D 项目的,但我认为这并不重要):

我有可以提供各种类型内容的内容提供程序(“纹理”、“字符串”类型的对象...)因此我创建了一个抽象的泛型类和一个接口,使我的架构看起来像这样

接口架构、抽象类和实现它的具体类

此外,我有能够处理某种类型的内容的 Content Receivers 和具有一组此类Content Receivers的管理类。我想要接收器必须以如下样式处理给定提供者的内容的逻辑:

public void accept(IUIContentProvider provider){
    //1. Check if a receiver for the generic type of the provider exists
    
    //2. Ignore the call if no such receiver exists, otherwise pass the provider to this class and 
    //let it deal with it in some specific manner.
}

但是由于 C# 的强类型系统,使用多态似乎不可能做任何优雅的事情。我显然也无法显式转换 IUIContentProvider 。我什至不能使用抽象的基础方法,例如:

public abstract object provideContent()

并用例如覆盖它:

public override Texture provideContent(){...}

在这一点上,我开始怀疑在 C# 中为此目的使用泛型是否明智......

标签: c#unity3dgenerics

解决方案


你在你的抽象/通用类中说UIContentProvider<T>你想要这样的方法:

public abstract object ProvideContent();

并且您希望能够在您的具体实现中具有此覆盖TextProvider

public override string ProvideContent(){...};

但我认为你错过了抽象类中泛型的意义......如果你不使用类型参数 T 有什么意义?

这不是你想要的吗?

public interface IUIContentProvider<T>
{
    T ProvideContent();
}

public abstract class UIContentProvider<T> : IUIContentProvider<T>
{
    public abstract T ProvideContent();
}


public class TextProvider : UIContentProvider<string>
{
    public override string ProvideContent()
    {
        return "";
    }
}

推荐阅读