从泛型类型列表中进行C#转换

从泛型类型列表中进行C#转换,c#,generics,C#,Generics,我们有以下接口,用于定义实体的索引方式(使用lucene): 我的问题是如何在IndexQueue上创建泛型IndexTask对象列表,并在执行任务时转换为相关的实体类型 由于我的实体实现了IIndexable接口,我可以存储IndexTask列表,但这将导致在上述代码中“task.Definition”解析为IIndexDefinition 谢谢 本 更新 我考虑在索引任务“IndexTask”的基类上公开以下内容: 然后在IndexTask上重写: public override T

我们有以下接口,用于定义实体的索引方式(使用lucene):

我的问题是如何在IndexQueue上创建泛型
IndexTask
对象列表,并在执行任务时转换为相关的实体类型

由于我的实体实现了IIndexable接口,我可以存储
IndexTask
列表,但这将导致在上述代码中“task.Definition”解析为
IIndexDefinition

谢谢 本

更新

我考虑在索引任务“IndexTask”的基类上公开以下内容:

然后在IndexTask上重写:

    public override Type GetEntityType() {
        return this.entity.GetType();
    }

    public override Type GetDefinitionType() {
        return this.definition.GetType();
    }
如果我在队列中存储了IndexTaskBase列表,那么我是否可以使用这些方法转换我的类型-可能使用System.ComponentModel.TypeConverter?

您是否可以重写:

service.IndexEntity(task.Entity, task.Definition);
在任务方法上执行以下操作:

task.IndexWithService(service);
然后,在IndexWithService中,您可以执行以下操作:

service.IndexEntity(this.Entity, this.Definition);

IndexWithService
可以在非泛型的任务基类上实现,并且列表可以是该类型。

我在这里进行扩展,但是如果您使用的是.NET 4.0,您应该能够为接口类型参数使用新的协方差和逆变指示符(更多信息,请访问:)并将IIndexDefinition接口上的类型参数T标记为“in”。这将有助于将这些实现的集合放在一起?您可以添加此方法的定义吗?@Pieter-AddItem只将该项添加到列表中。问题是如何定义该列表,以及如何在枚举时将项目转换回其原始类型。我用自己的一个想法更新了我的问题。这正是我最终要做的(我使用了IIndexTask接口,而不是使用抽象类)。离开电脑几小时就能完成的事情真是太神奇了!
        var tasks = IndexQueue.Instance.Items;

        var service = new IndexService();

        foreach (var task in tasks) {
            service.IndexEntity(task.Entity, task.Definition);
        }
    public abstract Type GetEntityType();
    public abstract Type GetDefinitionType();
    public override Type GetEntityType() {
        return this.entity.GetType();
    }

    public override Type GetDefinitionType() {
        return this.definition.GetType();
    }
service.IndexEntity(task.Entity, task.Definition);
task.IndexWithService(service);
service.IndexEntity(this.Entity, this.Definition);