泛型中的C#递归泛型

时间:2015-07-08 08:25:38

标签: c# generics

我正在使用DDD一段时间,并为实体找到Ayende's base class构造。我想构建一个只有最必要的对象的基础组件。这就是我提出的(简化而没有实现):

public abstract class BaseEntity<T, TKey> where T : BaseEntity<T, TKey> { }

public interface IAggregateRoot { }

public interface IUnitOfWork
{
    void Commit();
}

// I am open to changes if they help
public interface IWriteUnitOfWork : IUnitOfWork
{
    void Insert<TAggregateRoot, T, TKey>(TAggregateRoot aggregateRoot)
        where TAggregateRoot : BaseEntity<T, TKey>, IAggregateRoot
        where T : BaseEntity<T, TKey>;
}

一切都很好,直到我在项目中使用这个结构。这是没有实施的简化项目的具体细节:

public abstract class Entity : BaseEntity<Entity, Guid> { }

public class Customer : Entity, IAggregateRoot { }

public abstract class Context : IWriteUnitOfWork
{
    public void Insert<TAggregateRoot, T, TKey>(TAggregateRoot aggregateRoot)
        where TAggregateRoot : BaseEntity<T, TKey>, IAggregateRoot
        where T : BaseEntity<T, TKey> { }

    public void Commit() { }
}

public class MyContext : Context { }

public class ExampleThatWorks
{
    public void Something()
    {
        IWriteUnitOfWork myContext = new MyContext();
        var customer = new Customer();

        // this works
        myContext.Insert<Customer, Entity, Guid>(customer);
    }
}

public class ExampleThatIWant
{
    public void Something()
    {
        IWriteUnitOfWork myContext = new MyContext();
        var customer = new Customer();

        // this doesn't work
        myContext.Insert(customer);
    }
}

我的问题在于IWriteUnitOfWork接口的Insert方法。我想写它,以便每次我想在ExampleThatIWant中使用它时都不必编写所有通用的东西。然而,如果没有一个非常好的理由,我不想改变我的基础组件。

这可能吗?怎么样?我也对其他方法持开放态度。

感谢。

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

public abstract class BaseEntity<T, TKey> where T : BaseEntity<T, TKey> { }

public interface IAggregateRoot { }

public interface IUnitOfWork
{
    void Commit();
}

public interface IWriteUnitOfWork : IUnitOfWork
{
    void Insert<T>(T aggregateRoot)
        where T : BaseEntity<T, Guid>, IAggregateRoot;
}

public abstract class Entity<T, TKey> : BaseEntity<T, TKey>
    where T : BaseEntity<T, TKey>
{ }

public class Customer : Entity<Customer, Guid>, IAggregateRoot { }

public abstract class Context : IWriteUnitOfWork
{
    public void Insert<T>(T aggregateRoot)
        where T : BaseEntity<T, Guid>, IAggregateRoot
    { }

    public void Commit() { }
}

public class MyContext : Context { }

public class ExampleThatIWant
{
    public void Something()
    {
        IWriteUnitOfWork myContext = new MyContext();
        var customer = new Customer();

        myContext.Insert(customer);
    }
}