简体   繁体   English

以泛型类型输入作为参数的 Lambda 表达式

[英]Lambda Expression with Generic Type Input as Parameter

I want to make a method accept Expression like this我想让一个方法接受这样的表达式

public class MyClass
{
  public void MyMethod( Expression<Func<T> expression)
  {}
}

public class FooClass
{
  public string Foo { get; set; }
}

MyClass A = new MyClass();

A.MyMethod( (FooClass x) => x.Foo );

How can I implement this?我该如何实施? thank you in advance.先感谢您。

First of all, what is your goal in implementing such a class?首先,您实现这样一个 class 的目标是什么? What result do you want to return?你想返回什么结果? Here is an example of how to use it for you这是一个如何为您使用它的示例

public class MyClass
{
  IQueryable<FooClass> myQuery;
  public MyClass()
  {
     myQuery = new List<FooClass>() { new FooClass() { Foo = "foo1"}, new FooClass() { Foo = "foo1" }, new FooClass() { Foo = "foo2" } }.AsQueryable();
  }
  public IQueryable<FooClass> WhereMethod(Expression<Func<FooClass, bool>> predicate)
  {
    try
    {
      return myQuery.Where(predicate);
    }
    catch
    {
      return null;
    }
  }
  public IQueryable<TResult> SelectMethod<TResult>(Expression<Func<FooClass, TResult>> predicate)
  {
     try
     {
       return myQuery.Select(predicate);
     }
     catch
     {
        return null;
     }
  }
}
public class FooClass
{
   public string Foo { get; set; }
}

now use现在使用

MyClass myClass = new MyClass();
var fooList = myClass.WhereMethod(a => a.Foo == "foo1").ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用lambda表达式作为泛型类型的参数的构造方法 - Constructor with lambda expression as parameter of generic type 如何将Generic Type参数传递给lambda表达式? - How to pass Generic Type parameter to lambda expression? 使用Lambda表达式和AutoFac中的参数注册通用类型 - Register Generic Type using lambda expression with a parameter in AutoFac 解决通用lambda表达式类型 - Resolving generic lambda expression type 在匿名方法、lambda 表达式、查询表达式或本地 function 中使用的通用参数类型 - Generic parameter type to use inside an anonymous method, lambda expression, query expression, or local function 替换lambda表达式中的参数类型 - Replace parameter type in lambda expression 在运行时检查属性类型,并将相同的类型赋予通用lambda表达式参数T - Check property type at runtime and give the same type to Generic lambda expression parameter T 如何将 lambda 表达式参数类型转换为另一种泛型类型? - How can I convert lambda expression parameter type to another generic type? 反射:使用泛型参数和lambda表达式作为参数的方法 - Reflection: method with generic argument and lambda expression as parameter 用lambda表达式参数调用泛型方法的反射 - Reflection to call generic method with lambda expression parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM