繁体   English   中英

如何键入约束泛型场景

[英]How to type constrain generics scenario

我正在尝试创建一个自定义Collection<X, Y...> : ICollection<X>, IList<Y> 它继承自ICollection<T>IList<T>因为我决定使用通用版本,因为它们更现代。 这是我需要的约束:

  • 类型T (值类型或引用类型)的项可以添加到集合中。
  • 还可以无限添加IEnumerable<T>IEnumerable<IEnumerable<T>>类型的项目,依此类推:)

如何使用这些约束创建泛型类,即 where 子句是什么? 这甚至可能吗? 这是使用非泛型ICollectionIList并且没有泛型的合适地方吗?

正如MSDN 上所述,类型约束是可能的,您可以接受一个或多个约束。

还要检查WHERE 用法

希望能帮助到你。

这是你想要的吗?

public interface IBlock<T> 
    where T : IBlock<T>
{
}

public class Block<T> : Collection<T>, IBlock<Block<T>>
{        
}


class Program
{
    static void Main(string[] args)
    {
        var list_1=new Block<int[]>();
        list_1.Add(new int[] { 1, 2, 3} );
        list_1.Add(new int[] { 4, 5} );
        var list_2=new Block<int[]>();
        list_2.Add(new int[] { -1, 4} );
        list_2.Add(new int[] { 2, 6, 8} );
        var list_list =new Block<Block<int[]>>();
        list_list.Add(list_1);
        list_list.Add(list_2);

        int x=list_list[1][0][1];
        // x=4
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM