我已经开始使用 C# 表达式构造,但我有一个关于如何在以下情况中应用泛型的问题:
假设我有一个 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
中的赋值中我得到了编译错误:
Cannot implicitly convert type System.Linq.Expression.Expression< MyObject, string, bool > to System.Linq.Expression.Expression < MyBusinessObject, string, bool >>
在这种情况下,我可以将泛型与 C# 表达式一起使用吗?我想在 DefineStringIndexer 中使用 T,这样我就可以避免在 lambda 中强制转换 MyObject。
最佳答案
分配将不起作用,因为 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);
}
关于c# - C# Expression<TDelegate> 的通用约束 - 无法隐式转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11452287/