简体   繁体   中英

How to type constrain generics scenario

I am trying to make a custom Collection<X, Y...> : ICollection<X>, IList<Y> of sorts. It inherits from ICollection<T> , and IList<T> because I decided to go with the generic versions as they are more modern. Here are the constraints I need:

  • items of type T (value types or reference types) can be added to the collection.
  • Items of type IEnumerable<T> or IEnumerable<IEnumerable<T>> so forth and so on infinitely down the line can also be added :)

How can you make a Generic class with these constraints, ie what would the where clause be? Is this even possible? Would this be an appropriate place to use the non-generic ICollection , IList and no generics?

As described on MSDN type constrain is possible and you can accept one or multiple constraints.

Also check WHERE usage

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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