带C#表达式的一般约束<;TDelegate>;-无法隐式转换类型
我已经开始使用C#表达式构造,我有一个关于泛型在以下情况下如何应用的问题: 假设我有一个类型带C#表达式的一般约束<;TDelegate>;-无法隐式转换类型,c#,generics,lambda,expression,C#,Generics,Lambda,Expression,我已经开始使用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,
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
中的赋值中,我得到了编译错误:
无法隐式转换类型
System.Linq.Expression.Expression在这种情况下,我可以将泛型与C#表达式一起使用吗?我想在DefineStringIndexer中使用T,这样我就可以避免在lambda中投射MyObject。这对您更有效吗 编辑:将
添加到约束-认为您需要:)
类MyObject
{
//这是一个字符串索引器表达式,用于在对象位于MyObject集合中时定义字符串索引器
公共表达式StringIndexExpression{get;private set;}
//我在Set StringIndexExpression中使用此方法,T是MyObject的一个子类型
受保护的无效定义索引器(表达式>表达式)
其中T:MyObject//认为需要此约束才能同时具有泛型参数
{
StringIndexExpression=表达式;
}
}
然后:
公共类MyBusinessObject:MyObject
{
公共字符串名称{get;set;}
公共MyBusinessObject()
{
Name=“测试”;
DefineStringIndexer((项,值)=>item.Name==value);
}
}
分配将不起作用,因为Func
类型与Func
分配不兼容。但是,这两个函子的参数是兼容的,因此可以添加包装器使其工作:
protected void DefineStringIndexer<T>(Func<T,string,bool> expresson) where T : MyObject {
StringIndexExpression = (t,s) => expression(t, s);
}
受保护的无效定义索引器(Func expresson),其中T:MyObject{
StringIndexExpression=(t,s)=>表达式(t,s);
}
您的代码无法工作,因为.NET不支持可变类型之间的协方差。您可以使用不可变类型(但这可能不适合您!)。您可以尝试DefineStringIndexer((项目,值)=>((MyBusinessObject)项目)。名称==值)代码>。。那可能有用!或者,您也可以将MyObject
设置为泛型,并使用MyBusinessObject:MyObject
然后为类型为TGood tip:)的表达式
设置类型参数,但您没有想到!
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);
}
}
protected void DefineStringIndexer<T>(Func<T,string,bool> expresson) where T : MyObject {
StringIndexExpression = (t,s) => expression(t, s);
}