Generic type in generic collection

北城以北 提交于 2020-01-04 17:51:09

问题


I have generic type that looks like:

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

I then have a collection of these instances. What is the cleanest way to pass through the type constraints?

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

Is there perhaps a better way to design this? I think that specifying

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

seems awkward. Might be my only option though....


回答1:


When creating a generic class, all generic type parameters of all objects used in all members of the generic class must be resolvable at compile time.

You can have type parameters that are specific instances of other generic types - for example:

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

But if you want the type parameters of GenericClass to be generic themselves, then all of those types need to be part of the class declaration, as you've written:

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

Sorry if it seems awkward, but that's your only option.




回答2:


I think the collection will need the same constraints as GenericClass:

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



回答3:


I think your solution is

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



回答4:


I think this is what you really want..

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



回答5:


you haven't declared it as a class!

public class GenericCollection<V>


来源:https://stackoverflow.com/questions/2560902/generic-type-in-generic-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!