General restrictions with C # <TDelegate> expression - it is not possible to implicitly convert a type

I started using C # expression constructors, and I had a question about how generic tools are applied in the following situation:

I have a type MyObject , which is the base class for many different types. Inside this class, I have the following code:

 // This is a String Indexer Expression, used to define the string indexer when the object is in a collection of MyObjects public Expression<Func<MyObject, string, bool>> StringIndexExpression { get; private set;} // I use this method in Set StringIndexExpression and T is a subtype of MyObject protected void DefineStringIndexer<T>(Expression<T, string, bool>> expresson) where T : MyObject { StringIndexExpression = expression; } 

This is how I use DefineStringIndexer :

 public class MyBusinessObject : MyObject { public string Name { get; set; } public MyBusinessObject() { Name = "Test"; DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value); } } 

However, in the assignment inside DefineStringIndexer I get a compilation error:

It is not possible to implicitly convert the type System.Linq.Expression.Expression <MyObject, string, bool> to System.Linq.Expression.Expression <MyBusinessObject, string, bool โ†’

Can I use Generics with C # expressions in this situation? I want to use T in DefineStringIndexer, so I can avoid the MyObject exception inside the lambda.

+4
source share
2 answers

The destination will not work, because the type Func<MyBusinessObject,string,bool> not compatible with the destination Func<MyObject,string,bool> . However, the parameters of the two functors are compatible, so you can add a wrapper to make it work:

 protected void DefineStringIndexer<T>(Func<T,string,bool> expresson) where T : MyObject { StringIndexExpression = (t,s) => expression(t, s); } 
+3
source

Will this work better for you?

Edit: added <T> to the restriction - think what you need :)

 class MyObject<T> { // This is a String Indexer Expression, used to define the string indexer when the object is in a collection of MyObjects public Expression<Func<T, string, bool>> StringIndexExpression { get; private set;} // I use this method in Set StringIndexExpression and T is a subtype of MyObject protected void DefineStringIndexer<T>(Expression<T, string, bool>> expresson) where T : MyObject<T> // Think you need this constraint to also have the generic param { StringIndexExpression = expression; } } 

then

 public class MyBusinessObject : MyObject<MyBusinessObject> { public string Name { get; set; } public MyBusinessObject() { Name = "Test"; DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value); } } 
0
source

All Articles