简体   繁体   English

如何键入约束泛型场景

[英]How to type constrain generics scenario

I am trying to make a custom Collection<X, Y...> : ICollection<X>, IList<Y> of sorts.我正在尝试创建一个自定义Collection<X, Y...> : ICollection<X>, IList<Y> It inherits from ICollection<T> , and IList<T> because I decided to go with the generic versions as they are more modern.它继承自ICollection<T>IList<T>因为我决定使用通用版本,因为它们更现代。 Here are the constraints I need:这是我需要的约束:

  • items of type T (value types or reference types) can be added to the collection.类型T (值类型或引用类型)的项可以添加到集合中。
  • Items of type IEnumerable<T> or IEnumerable<IEnumerable<T>> so forth and so on infinitely down the line can also be added :)还可以无限添加IEnumerable<T>IEnumerable<IEnumerable<T>>类型的项目,依此类推:)

How can you make a Generic class with these constraints, ie what would the where clause be?如何使用这些约束创建泛型类,即 where 子句是什么? Is this even possible?这甚至可能吗? Would this be an appropriate place to use the non-generic ICollection , IList and no generics?这是使用非泛型ICollectionIList并且没有泛型的合适地方吗?

As described on MSDN type constrain is possible and you can accept one or multiple constraints.正如MSDN 上所述,类型约束是可能的,您可以接受一个或多个约束。

Also check WHERE usage还要检查WHERE 用法

Hope it helps.希望能帮助到你。

Is this what you want?这是你想要的吗?

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