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

时间:2010-10-20 16:32:43

标签: c# generics

我们使用以下接口来定义实体应如何编入索引(使用lucene):

public interface IIndexDefinition<T> where T : IIndexable {
    Document Convert(T entity);
}

这意味着我们可以保持索引服务非常简单。因此,要索引我们拥有的实体:

   IndexResult IndexEntities<TEntity>(IEnumerable<TEntity> entities, 
                                      IIndexDefinition<TEntity> definition) 
                                                    where TEntity : IIndexable;

为了支持对索引的增量更新,我们创建了一个索引队列。索引队列包含要对lucene索引执行的任务的线程安全列表。

本质上,IndexTask只是一种存储更新实体和索引定义的方法。我们目前的课程是:

public class IndexTask<TEntity>
{
    private TEntity entity;
    private IIndexDefinition<TEntity> definition;

    public IndexTask(TEntity entity, IIndexDefinition<TEntity> definition)
    {
        this.entity = entity;
        this.definition = definition;
    }

    public TEntity Entity { get { return this.entity; } }
    public IIndexDefinition<TEntity> Definition { get { return definition; } }
}

当实体更新时,我们将在事件处理程序中包含以下内容:

        var task = new IndexTask<Car>(car, new CarIndexDefinition());
        IndexQueue.Instance.AddItem(task); // this doesn't work

并执行队列中的任务:

        var tasks = IndexQueue.Instance.Items;

        var service = new IndexService();

        foreach (var task in tasks) {
            service.IndexEntity(task.Entity, task.Definition);
        }

我的问题是如何在IndexQueue上创建通用IndexTask<TEntity>对象列表,并在执行任务时强制转换为相关实体类型。

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

由于 本

更新

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

    public abstract Type GetEntityType();
    public abstract Type GetDefinitionType();

然后覆盖IndexTask:

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

    public override Type GetDefinitionType() {
        return this.definition.GetType();
    }

如果我在队列中存储IndexTaskBase列表,我可以使用这些方法转换我的类型 - 也许使用System.ComponentModel.TypeConverter?

1 个答案:

答案 0 :(得分:2)

你可以改写:

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

关于任务方法的以下内容:

task.IndexWithService(service);

然后,在IndexWithService内部,你可以这样做:

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

IndexWithService可以在不是通用的Task的基类上实现,列表可以是该类型。

相关问题