小编Jer*_*e S的帖子

使用不同的泛型参数初始化泛型集合数组

在开发我的一个项目期间,我遇到了有关泛型类型的问题.

该项目要求我编写一个类作为列表对象的源.假设我有以下课程:

public class TablesProvider
{
    private readonly List[] _tables;

    public TablesProvider()
    {
        // initialize the tables var here....
    }

    public List<TItem> GetTable<TItem>()
    {
        return (List<TItem>)_tables.Single(x => x is List<TItem>);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个类显然不起作用,因为List类型是泛型类型,因此应该指定泛型参数.

所以我做了一个名为的抽象类型MyList,它将通过一个更具体的类型派生,MyList<TItem>以逃避这个要求,并编辑TablesProvider了一点.

public class TablesProvider
{
    private readonly MyList[] _tables;

    public TablesProvider()
    {
        // initialize the tables var here....
    }

    public MyList<TItem> GetTable<TItem>()
    {
        return (MyList<TItem>)_tables.Single(x => x is MyList<TItem>);
    }
}

public abstract class MyList
{
    // ...
} …
Run Code Online (Sandbox Code Playgroud)

c# oop generics collections

5
推荐指数
1
解决办法
60
查看次数

标签 统计

c# ×1

collections ×1

generics ×1

oop ×1