且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 lambda 表达式中检索属性名称

更新时间:2022-06-27 05:53:05

我发现另一种方法是强类型化源和属性并显式推断 lambda 的输入.不确定这是否是正确的术语,但结果如下.

I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
    var expression = (MemberExpression)action.Body;
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

然后这样称呼它.

GetInfo((User u) => u.UserId);

瞧,它起作用了.