Get property name from Func<t, T>

本文关键字:gt property lt from Func Get name | 更新日期: 2023-09-27 18:20:08

如何从Func<T, TResult>获取属性名称?

有很多帖子如何从Expression而不是从Func 获得道具名称

_resultViewModel.SelectMeasurement(si => si.Height, vm => vm.HeightImg); // this is usage... I need to get "Height"
public void SelectMeasurement(Func<ScanInfo, double> measurement, Func<ResultViewModel, ImageSource> image)
{
    //some stuff
}

Get property name from Func<t, T>

您无法获得"属性名称";从Func<T, TResult>;属性";以及任何";name";,当构造委托时。

此外,委托可以通过某种不同的方式获得其返回值,而不是成员访问:

Func<Foo, string> = foo => "bar";

这与表达式大小写(Expression<Func<T, TResult>>)不同,因为表达式表示一些代码,这些代码可以编译为委托,并且可以解析。

如果您知道您将使用旨在访问模型属性的简单委托,那么您可以使用类似的方法:

private static string GetFuncPropertyName<T, TResult>(Expression<Func<T, TResult>> expr)
{
    if (expr.Body is not MemberExpression memberExpression)
        throw new ArgumentException($"The provided expression contains a {expr.GetType().Name} which is not supported. Only simple member accessors (fields, properties) of an object are supported.");
    return memberExpression.Member.Name;
}

您可以将常规lambda委托传递到其中:

private class MyClass { public string MyProperty { get; set; } }
...
var propertyName = GetFuncPropertyNameT<MyClass, string>(m => m.MyProperty);

如果您不确定,您将不得不获得实际的方法体func.GetMethodInfo().GetMethodBody();,将IL字节解析为字符串(这是一项非平凡的任务),然后对其进行解释。为了参考,您可以查看:https://www.codeproject.com/articles/14058/parsing-the-il-of-a-method-body