[英]C# recursive generics in generics
我在DDD上玩了一段時間,並發現了Ayende實體的基類構造。 我想只用最必要的對象構造一個基礎組件。 這是我想出的(無需實現即可簡化):
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一樣使用所有通用的東西。 但是,如果沒有充分的理由,我不想更改基礎裝配。
這有可能嗎? 我也對其他方法持開放態度。
謝謝。
這對您有用嗎?
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.