4

我已经开始使用 C# Expression 构造,并且我有一个关于泛型如何在以下情况下应用的问题:

考虑我有一个类型MyObject,它是许多不同类型的基类。在这个类中,我有以下代码:

// 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;
}

这就是我的使用方式DefineStringIndexer

public class MyBusinessObject : MyObject
{

   public string Name { get; set; }

   public MyBusinessObject() 
   {
       Name = "Test";
       DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value);
   }

}

但是在里面的赋值中DefineStringIndexer我得到了编译错误:

无法将类型 System.Linq.Expression.Expression< MyObject, string, bool > 隐式转换为 System.Linq.Expression.Expression < MyBusinessObject, string, bool >>

在这种情况下,我可以将泛型与 C# 表达式一起使用吗?我想在 DefineStringIndexer 中使用 T ,这样我就可以避免在 lambda 中转换 MyObject 。

4

2 回答 2

3

分配将不起作用,因为Func<MyBusinessObject,string,bool>类型与分配不兼容Func<MyObject,string,bool>。但是,这两个函子的参数是兼容的,因此您可以添加一个包装器以使其工作:

protected void DefineStringIndexer<T>(Func<T,string,bool> expresson) where T : MyObject {
    StringIndexExpression = (t,s) => expression(t, s);
}
于 2012-07-12T13:07:26.217 回答
0

这对你会更好吗?

编辑:添加<T>到约束-认为您将需要它:)

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; 
    } 
}

然后:

public class MyBusinessObject : MyObject<MyBusinessObject>
{ 

   public string Name { get; set; } 

   public MyBusinessObject()  
   { 
       Name = "Test"; 
       DefineStringIndexer<MyBusinessObject>((item, value) => item.Name == value); 
   } 

} 
于 2012-07-12T13:01:05.240 回答