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

Dan*_*wna 1 .net c# 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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是如何调用TheFunction?目标是使用Expression>,以便在TheFunction中检索除其他内容之外的属性名称.

我想要这样的东西:

//...
TheFunction((foo f)=> f.bar);
//...
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试它会说,类型参数不能从使用中产生,我应该尝试指定它们,但如何?

Ond*_*cny 5

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

public void TheFunction<TArg, TResult> (Expression<Func<TArg, TResult>> action) { … }
Run Code Online (Sandbox Code Playgroud)

那么这段代码将编译正常:

new Program().TheFunction((foo b) => b.bar);
Run Code Online (Sandbox Code Playgroud)

附注:Main是一个静态方法,因此您需要先实例化Program才能调用TheFunction.