【发布时间】:2012-07-12 12:52:53
【问题描述】:
我已经开始使用 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 里面的赋值中我得到了编译错误:
不能隐式转换类型 System.Linq.Expression.Expression to System.Linq.Expression.Expression >
在这种情况下,我可以将泛型与 C# 表达式一起使用吗?我想在 DefineStringIndexer 中使用 T,这样我就可以避免在 lambda 中强制转换 MyObject。
【问题讨论】:
-
您的代码将无法工作,因为 .NET 不支持可变类型之间的协变。您可以使用不可变类型(但这可能对您不起作用!)。你可以试试
DefineStringIndexer<MyObject>((item , value) => ((MyBusinessObject)item).Name == value);.. 这可能有用! -
或者,您也可以将
MyObject设为泛型并使用MyBusinessObject : MyObject<MyBusinessObject>,然后为T 类型的Expression创建类型参数
标签: c# generics lambda expression