我如何能够创建一个List< T>包含一个开放的通用接口? [英] How am I able to create A List<T> containing an open generic Interface?

查看:179
本文介绍了我如何能够创建一个List< T>包含一个开放的通用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List,它必须包含 IInteract 对象。但是 IInteract 是一个需要2个类型参数的通用接口。

I have a List which must contain IInteract Objects. But IInteract is a generic interface which requires 2 type arguments.

我的主要想法是迭代对象列表和互动,如果他们没有互动。
所以我有这个对象

My main idea is iterate through a list of Objects and "Interact" one with another if they didn't interact yet. So i have this object

List<IObject> WorldObjects = new List<IObject>();

和这一个:

and this one:

private List<IInteract> = new List<IInteract>();

除了我无法编译最后一行,因为 IInteract 需要2个类型参数。但我不知道这些论点是什么,直到我添加它们。我可以添加类型A和A的对象或类型B和C的对象之间的交互。

Except I can't compile the last line because IInteract requires 2 type arguments. But I don't know what the arguments are until I add them. I could add interactions between Objects of Type A and A... or Objects of Type B and C.

我想要创建交互类, 表演对象和目标对象,但我希望它们独立于对象...因此,我可以在...之间添加交互... SuperUltraClass和...一个整数

I want to create "Interaction" classes which do something with the "acting" object and the "target" object, but I want them to be independent from the objects... so I could add an Interaction between for instance... "SuperUltraClass" and... an "integer".

我是否使用了错误的方法?

Am I using the wrong approach?

推荐答案

假设IInteract被定义为类似于

Assuming IInteract is defined as something like

interface IInteract<T1, T2>

并且您正在将它用于Foo类的字段:

and you are using it for a field of a class Foo:

class Foo
{
  List<IInteract...> field;
}

然后,如果您想推迟决定绑定到IInteract的类型类型的参数你需要参数化容器类:

Then if you want to defer the decision of what types to bind to the IInteract type arguements you need to parameterize the container class:

class Foo<T1, T2>
{
   List<IInteract<T1, T2>> field;
}

当你定义一个具体实例化的时候,这里的IInteract类型参数将被绑定例如: var x = new Foo< int,double>()。这将导致IInteract字段的类型为 IInteract< int,double> 用于Foo泛型类型的特定实例化。

The type arguments to IInteract here will be bound when you define a concrete instantiation of the container class, like: var x = new Foo<int, double>(). This will cause the IInteract field to be of type IInteract<int, double> for that particular instantiation of the Foo generic type.

这篇关于我如何能够创建一个List&lt; T&gt;包含一个开放的通用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆