C # compiler error 'Parameter must be entered safe. Invalid variance. A parameter of type 'T' must be invariantly valid for the expression <TDelegate> '

I want to use my interface together (the interface should be a co-option), but the compiler gave me an error. C # compiler error: - 'The parameter must be entered safely. Invalid variance. A parameter of type "T" must be invariantly valid in "Expression" . This is my code:

interface IRepository<out T> where T : BaseEntity { IEnumerable<T> Find(Expression<Func<T, bool>> predicate); T FindById(Guid id); } 
+6
source share
1 answer

You declared T as covariant (using the out keyword), but you cannot accept covariant parameters:

(MSDN)

In general, a covariant type parameter can be used as the return type of a delegate, and contravariant type parameters can be used as parameter types. For an interface, covariant type parameters can be used as return types of interface methods, and contravariant type parameters can be used as parameter types of the Methods interface.

Func<T, bool> takes an argument T and returns bool violation of this rule. You can mark this as contravariant, but you return T in the next function.

You can try and beat it by taking two type parameters (one covariant and one contravariant), something like:

 interface IRepository<out T, in U> where T : BaseEntity where U : BaseEntity { IEnumerable<T> Find(Expression<Func<U, bool>> predicate); T FindById(Guid id); } 

I seriously doubt what you are looking for, and I'm not sure if it will even compile / work, but it can help.

+7
source

Source: https://habr.com/ru/post/970974/


All Articles