![](/img/trans.png)
[英]How to fix this error? Invalid variance: The type parameter 'T' must be invariantly valid on
[英]c# compiler error 'Parameter must be input safe. Invalid variance. The type parameter 'T' must be invariantly valid on Expression<TDelegate> '
我想共同使用我的接口(接口必須是共變體)但編譯器給我錯誤c#編譯器錯誤: - '參數必須輸入安全。 方差無效。 類型參數'T'必須在'Expression'上不變有效這是我的代碼:
interface IRepository<out T> where T : BaseEntity
{
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
T FindById(Guid id);
}
您將T
聲明為協變(使用out
關鍵字)但您不能使用協變參數:
通常,協變類型參數可以用作委托的返回類型,逆變類型參數可以用作參數類型。 對於接口,協變類型參數可以用作接口方法的返回類型,逆變類型參數可以用作接口方法的參數類型。
Func<T, bool>
接受一個T
參數並返回一個違反此規則的bool
。 您可以將其標記為逆變,但在下一個函數中返回T
您可以通過采用兩個類型參數(一個協變量和一個逆變量) 來嘗試擊敗它,例如:
interface IRepository<out T, in U> where T : BaseEntity
where U : BaseEntity
{
IEnumerable<T> Find(Expression<Func<U, bool>> predicate);
T FindById(Guid id);
}
我非常懷疑它在尋找什么,我不確定它是否會編譯/工作,但它可能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.