是否可以将具有不同泛型/类型的对象列表作为参数

Acc*_*ubi 3 c# generics

考虑以下代码:

class Collision<type1, type2> 
{
    // further Code
}
Run Code Online (Sandbox Code Playgroud)

是否有可能(例如)LinkedList<>具有通用Collision作为其参数?换句话说:我可以以某种方式实现一个LinkedList<>接受碰撞对象的各种参数吗?

public LinkedList< Collision<Unit, Unit> > collisionList = new LinkedList< Collision<Unit,Unit> >();
Run Code Online (Sandbox Code Playgroud)

用这种方法我用的基类Unit的两个子类的替代PlayerEnemy.但我也有一个Environment不是子类的类,但也应该是一个可能的参数Collision.

提前致谢!

Alb*_*rto 6

一种方法是使用接口:

interface ICollision
{
    object PropertyOfType1{get;}
    object PropertyOfType2{get;}
}
Run Code Online (Sandbox Code Playgroud)

然后是从该接口继承的泛型类:

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;}
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用界面创建链接列表:

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

collisionList.AddLast(new Collision<int,int>());
collisionList.AddLast(new Collision<double,double>());
Run Code Online (Sandbox Code Playgroud)