我喜歡將我的定義與我的實現分開。我有一個接口實體:限制泛型在特定情況下失敗
public interface Entity<E> where E : Entity<E>
{
EntityId EntityId { get; }
bool ReadOnly { get; }
void FailIfReadOnly();
E Copy();
}
E是實際的實體類型,如Customer:
public interface Customer : Entity<Customer>
{
}
我的問題是FailIfReadOnly(執行):如果只讀== true,則拋出一個EntityIsReadOnlyException。
public class EntityIsReadOnlyException<E> where E : Entity<E>
{
public EntityIsReadOnlyException(E entity)
: base(string.Format("Entity {0} is read only", entity.EntityId))
{
}
}
public class EntityImpl<E> : Entity<E> where E : Entity<E>
{
public EntityImpl(E other)
{
}
public bool ReadOnly
{
get;
protected set;
}
public void FailIfReadOnly()
{
if (! ReadOnly) throw new EntityIsReadOnlyException<E>(this);
}
}
的throw new EntityIsReadOnlyException<E>(this);
導致編譯錯誤:
The best overloaded method match for 'EntityIsReadOnlyException.EntityIsReadOnlyException(E)' has some invalid arguments
Argument '1': cannot convert from 'EntityImpl' to 'E'
我可以這樣做:
EntityIsReadOnlyExcetion<Customer> exc = new EntityIsReadOnlyException<Customer>(customerImpl);
,甚至:
Entity<E> entity = new EntityImpl<E>(this);
但不是:
EntityIsReadOnlyException<E> exc = new EntityIsReadOnlyException<E>(this);
在這兩種情況下,E僅限於實體的子類。我的問題是,爲什麼我得到這個編譯錯誤?這可能很簡單。
接口上「where E:Entity」的用途是什麼? –
2009-12-06 21:48:57
這是一個遞歸定義是不是? IE類型限制是一個實體>? 這甚至可能嗎? –
Spence
2009-12-06 21:57:20
@marcgravell - 通常這種遞歸類型限制的目的是在基類中實現可以返回派生類型的克隆或副本。 – x0n 2009-12-06 22:05:35