![](/img/trans.png)
[英]C# Generics: there is no way to constrain a type to have a static method?
[英]How to type constrain generics scenario
我正在尝试创建一个自定义Collection<X, Y...> : ICollection<X>, IList<Y>
。 它继承自ICollection<T>
和IList<T>
因为我决定使用通用版本,因为它们更现代。 这是我需要的约束:
T
(值类型或引用类型)的项可以添加到集合中。IEnumerable<T>
或IEnumerable<IEnumerable<T>>
类型的项目,依此类推:) 如何使用这些约束创建泛型类,即 where 子句是什么? 这甚至可能吗? 这是使用非泛型ICollection
、 IList
并且没有泛型的合适地方吗?
这是你想要的吗?
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.