繁体   English   中英

泛型集合中的泛型类型

[英]Generic type in generic collection

我有通用类型,看起来像:

public class GenericClass<T, U> where T : IComparable<T>
{
    // Class definition here
}

然后我收集了这些实例。 通过类型约束的最简洁方法是什么?

public class GenericCollection<V> where V : GenericClass<T, U> // This won't compile
{
    private GenericClass<T, U>[] entries;

    public V this[index]
    {
        get{ return this.entries[index]; }
    }
}

有没有更好的方法来设计这个? 我认为具体说明

GenericCollection<T, U, V> where V : GenericClass<T, U> 

看起来很尴尬。 可能是我唯一的选择....

创建泛型类时,泛型类的所有成员中使用的所有对象的所有泛型类型参数必须在编译时可解析。

您可以将类型参数作为其他泛型类型的特定实例 - 例如:

public class GenericCollection<T> where T : GenericClass<int, string> { ... }

但是如果你希望GenericClass的类型参数本身是通用的,那么所有这些类型都需要成为类声明的一部分,正如你所写:

GenericCollection<T, U, V> where V : GenericClass<T, U> 

对不起,如果它看起来很尴尬,但这是你唯一的选择。

我认为该集合需要与GenericClass相同的约束:

public class GenericCollection<T, U> where T : IComparable<T>
{
    private GenericClass<T, U>[] entries;
}

我认为你的解决方案是

public class GenericClass<T, U> where T : IComparable<T>
{
     // Class definition here
}

public class GenericCollection<T,U>  where T : IComparable<T>
{
     private GenericClass<T, U>[] entries;
     public GenericClass<T, U> this[int index]
      {
         get{ return this.entries[index]; }
      }
}

我想这就是你真正想要的......

    class g<t, u> where t : IComparable<t>
{
}

class gc<t, u>
{
    private g<t, u>[] entries;

    public g<t, u> this[int index]
    {
        get { return this.entries[index]; }
    }
}

你还没有把它宣布为班级!

public class GenericCollection<V>

暂无
暂无

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

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