Is it possible to have a list of objects with different generics/types as parameters

StackOverflow https://stackoverflow.com/questions/23659020

  •  22-07-2023
  •  | 
  •  

consider the following Code:

class Collision<type1, type2> 
{
    // further Code
}

is it possible to have a (for instance) LinkedList<> which has a generic Collision as its Paramater? In other words: can I somehow implement a LinkedList<> which accepts Collision objects will all kinds of parameters?

public LinkedList< Collision<Unit, Unit> > collisionList = new LinkedList< Collision<Unit,Unit> >();

With this approach I used the base class Unit as a replacement for the two child classes Player and Enemy. But I also have a class Environment which isn't a child class but shall also be a possible Parameter for Collision.

Thanks in advance!

有帮助吗?

解决方案

An approach is to use an interface:

interface ICollision
{
    object PropertyOfType1{get;}
    object PropertyOfType2{get;}
}

and then a generic class that inherits from that interface:

class Collision<type1,type2>:ICollision
{
    public type1 PropertyOfType1 {get;set;}
    public type2 PropertyOfType2 {get;set;}

    object ICollision.PropertyOfType1
    {
        get{return PropertyOfType1;}
    }

    object ICollision.PropertyOfType2
    {
        get{return PropertyOfType2;}
    }
}

then you can create your linked list using the interface:

LinkedList<ICollision> collisionList  = new LinkedList<ICollision>();

collisionList.AddLast(new Collision<int,int>());
collisionList.AddLast(new Collision<double,double>());

其他提示

The Collection<T, K> can only take obejcts of T, K or its children. If Unit and Environment are in no direct relation you could use object:

Collision<object, object>

For the "or its children" to work you ned to use "covaraince":

interface ICollision<out T, out K> { }
class Collision<T, K> : ICollision<T, K> { }

and then make a list like:

var collisionList = new LinkedList<ICollision<Unit, Unit>>();

You need the interface as classes do not support covariance, but then you can add e.g. Collision<Player, Enemy> to the list.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top