小编Joh*_*man的帖子

如何在没有通配符的情况下使用C#泛型?

在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)

c# generics wildcard covariance

9
推荐指数
2
解决办法
1172
查看次数

标签 统计

c# ×1

covariance ×1

generics ×1

wildcard ×1