c# - C# Expression<TDelegate> 的通用约束 - 无法隐式转换类型

标签 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, 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/

相关文章:

c# - ThreadAbortException 有什么特别之处?

c# - MVC4 部分绑定(bind)模型到 ICollection 或 List

java - 无法在 Java 中形成带有两个问号的类型的表达式

ios - 泛型函数声明抛出错误

amazon-web-services - 如何在 lambda 函数中进行 Cognito 身份验证?

c# - Nancy Self Host 不调用 Module?

c# - 跨TCP客户端的双向通讯

typescript - TypeScript 中 lambda 返回类型的签名

swift - 无故使用泛型

hadoop - Lambda 架构 - 为什么使用批处理层