在 java 中,我非常习惯于使用泛型和通配符。像这样的事情:List<? extends Animal>
。这允许您拥有 Animals 子类型的集合并在每个元素上运行通用例程(例如makeNoise()
)。我正在尝试在 C# 中完成此操作,但有点困惑,因为没有通配符。
在领域方面,我们在这里所做的是使用 SQL SMO 库从我们的数据库中收集脚本。我们有一个基本接口类型,它被多次扩展以编写脚本和收集不同的对象(表、视图、函数等——这是 T)
public interface IScripter<T> where T : IScriptable
{
IList<T> CollectScripts(params...)
}
public abstract class AbstractScripter<T> : IScripter<T> where T : IScriptable
{
....
}
public class TableScripter : AbstractScripter<Table>
{
....
}
public class ViewScripter : AbstractScripter<View>
{
....
}
到现在为止还挺好。看起来像一个完全合理的对象层次结构对吗?这是我打算做的,直到我发现没有通配符:
public class Program
{
static void Main(string[] args)
{
// auto discover all scripter modules, table, view, etc
IList<Iscripter<? extends IScriptable>> allScripters = GetAllScripterModules();
foreach (IScripter<? extends IScriptable> scripter in allScripters)
{
IList<? extends IScriptable> scriptedObjects = scripter.CollectScripts(...);
// do something with scripted objects
}
}
}
现在既然<? extends IScriptable>
这里不存在,那我应该怎么做呢?我尝试了很多东西,泛型方法,只使用基本类型,各种讨厌的转换,但没有什么能真正奏效。
你会建议用什么来替换这IList<Iscripter<? extends IScriptable>
件作品?
TIA