c# - 如何将 Expression<Func<int>> 传递给函数

标签 c# .net linq lambda

假设以下程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Lambda {
    class Program {
        public void TheFunction<T> (Expression<Func<T>> action) { 
        /** logic **/
        }

        static void Main (string[] args) {    
            TheFunction(); //this will of course not compile,
                           // because the Lambda Expression is missing. 
        }
    }

    public class foo {
        public int bar { get; set; }
    }
}

这里的问题是如何调用TheFunction?目标是使用 Expression>,以便在 TheFunction 中检索 Property 名称以及其他内容。

我想要这样的东西:

//...
TheFunction((foo f)=> f.bar);
//...

但是当我尝试时它会说,不能从用法中推断出类型参数,我应该尝试指定它们,但是如何指定它们?

最佳答案

问题是(foo f) => f.barFunc<T> 不兼容.您的 lamba 函数接受一个 foo 类型的参数并返回 int ,因此你必须声明 TheFunction这样:

public void TheFunction<TArg, TResult> (Expression<Func<TArg, TResult>> action) { … }

然后这段代码可以正常编译:

new Program().TheFunction((foo b) => b.bar);

旁注:Main是一个静态方法,因此您需要实例化 Program首先可以调用TheFunction .

关于c# - 如何将 Expression<Func<int>> 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20069089/

相关文章:

c# - 为必应 map 的 Silverlight 应用程序创建热图

c# - C# 中 pretty-print 异常

c# - 更改类名后是否可以恢复通过 "BinaryFormatter"序列化的对象?

c# - 为此 : 使用 linq

c# - PLINQ 与 LINQ : OutOfMemoryException for LINQ but not PLINQ

c# - c# 可执行控制台应用程序的生命周期(如果有)是什么?

c# - C# 列表理解简介

c# - LINQ to SQL : Invalid column name 'DepartureGate' , 即使该列存在

c# - 如何通过 FieldInfo.GetValue() 获取 Nullable<T> (而不是基础值)?

c# - 我在使用 ASP .NET 用户控件时遇到问题