c# - 在 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# 中为此目的使用泛型是否明智......
解决方案
你在你的抽象/通用类中说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 "";
}
}
推荐阅读
- android - GoogleSignIn requestPermissions onActivityResult 0 with Google Fitness steps/distance Scope
- firemonkey - C++ Builder 中的 Android JNI
- javascript - 获取嵌套数组中值最高的前 5 个元素
- react-native - 如何在 React Native 中返回变量?
- cypress - 赛普拉斯布尔断言
- c - 错误地打印双数
- redirect - 带有查询字符串的 IIS web.config 重写/重定向规则
- python - TypeError:参数“颜色”的标量值不是数字
- java - ZeroMQ(JeroMQ)接收调用导致java gc循环
- regex - 如何使用不同的关键字拆分熊猫字符串列?