在java中,我非常习惯使用泛型和通配符.比如:List<? extends Animal>.这允许您拥有一组动物的子类型,并在每个元素上运行通用例程(例如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>
{
....
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.看起来像一个完全合理的对象层次结构吧?这是我打算做的,直到我发现没有通配符:
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> …Run Code Online (Sandbox Code Playgroud) 我有两个接口:
public interface A {
void aMethod();
}
public interface B : A {
void bMethod();
}
Run Code Online (Sandbox Code Playgroud)
后来我基本上使用这样的字典:
Dictionary<int, A> dict = new Dictionary<int, B>();
Run Code Online (Sandbox Code Playgroud)
C#说我无法从右转换,即使我投了它.有没有办法在C#中使用泛型,以便这可以工作?如果我把它们作为抽象类,它似乎没问题,但我需要这些作为接口.
我正在寻找以下行的等效C#代码
private List<? extends HotSpot> hotSpots;
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢.