从表达式< Func< T,对象>获得实际的返回类型。实例 [英] Get actual return type from a Expression<Func<T, object>> instance

查看:100
本文介绍了从表达式< Func< T,对象>获得实际的返回类型。实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受 Expression< Func< T,object>> 实例的方法。我想得到由特定表达式实例返回的 actual 数据类型,而不是 object

I have a method that accepts a Expression<Func<T, object>> instance. I want to get at the actual data type being returned by a specific expression instance, rather than object.

我可以将其用于直接属性引用,因此,如果我传递表达式 x => x.IntegerProperty 我可以获得整数的类型引用。这种方法需要将其转换为MemberExpression。

I can get it to work for direct property references, so if I pass in the expression x => x.IntegerProperty I can get a Type reference for an integer. This approach requires converting it to a MemberExpression.

但是,我无法将其用于任意表达式。例如,如果表达式为 x => x.IntegerProperty.ToString()我想获取字符串的类型引用。我不能将其编译为MemberExpression,如果我只是 .Compile()并检查返回类型,我会得到对象。

However, I can't get it to work for arbitrary expressions. For instance, if the expression is x => x.IntegerProperty.ToString() I want to get a Type reference for a string. I can't compile this to a MemberExpression, and if I just .Compile() it and check the return type I get "object".

如何查看特定的表达式实例并得出实际的返回类型?

How can I look at the specific expression instance and derive the actual return type?

推荐答案

这样可能会成功。

public static Type GetObjectType<T>(Expression<Func<T, object>> expr)
{
    if ((expr.Body.NodeType == ExpressionType.Convert) ||
        (expr.Body.NodeType == ExpressionType.ConvertChecked))
    {
        var unary = expr.Body as UnaryExpression;
        if (unary != null)
            return unary.Operand.Type;
    }
    return expr.Body.Type;
}

这篇关于从表达式&lt; Func&lt; T,对象&gt;获得实际的返回类型。实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆