简体   繁体   中英

How make a collection of type which is generic type in c#

I have class like the following

public class Relation<T1, T2> where T1: Entity where T2: Entity
{
}

I want to make class derived from a list/collection which is of the type Relation

public class RelationList<T>: List<Relation>> 
{

}

I have tried in SO but couldn't get things right. Even right pointer to SO will also help

Because your Relation class is generic you have to specify generic types when you derive from Relation .

Either as

public class RelationList: List<Relation<MyEntity2, MyEntity2>>
{
}

or as

public class RelationList<T1, T2> : List<Relation<T1, T2>> 
        where T1: Entity
        where T2: Entity
{
}

If you want RelationList to be able to keep Relation<T1, T2> no matter how T1 and T2 is specified you should use additional interface:

public interface IRelation
{
}

public class Relation<T1, T2> : IRelation
    where T1: Entity where T2: Entity
{
}

public class RelationList : List<IRelation>
{
}

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