“System.Int32"类型的表达式不能用于返回类型“System.Object" [英] Expression of type 'System.Int32' cannot be used for return type 'System.Object'

查看:28
本文介绍了“System.Int32"类型的表达式不能用于返回类型“System.Object"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的脚本系统,用于打印标签.过去我用反射完成了这个没有问题,但我现在尝试用 Lambda 函数来完成,以便我可以缓存这些函数以供重用.

I am trying to produce a simple scripting system that will be used to print labels. I have done this in the past with reflection with no problem, but I am now trying to do it with Lambda functions so that I can cache the functions for reuse.

我目前的代码如下...

The code I have so far is as follows...

public static string GetValue<T>(T source, string propertyPath) {

    try {

        Func<T, Object> func;

        Type type = typeof(T);
        ParameterExpression parameterExpression = Expression.Parameter(type, @"source");
        Expression expression = parameterExpression;
        foreach (string property in propertyPath.Split('.')) {
            PropertyInfo propertyInfo = type.GetProperty(property);
            expression = Expression.Property(expression, propertyInfo);
            type = propertyInfo.PropertyType;
        }

        func = Expression.Lambda<Func<T, Object>>(expression, parameterExpression).Compile();

        object value = func.Invoke(source);
        if (value == null)
            return string.Empty;
        return value.ToString();

    }
    catch {

        return propertyPath;

    }

}

这在某些情况下似乎有效,但在其他情况下却失败了.问题似乎在于我试图将值作为对象返回 - 无论实际数据类型如何.我正在尝试这样做,因为我在编译时不知道数据类型是什么,但从长远来看,我只需要一个字符串.

This seems to work in some cases, but in others it fails. The problem seems to be in my trying to return the values as objects - irrespective of the actual data types. I am trying to do this because I do not know at compile time what the data type will be but in the long run, I only need a string.

每当我尝试访问 Int32 类型的属性时,我都会收到此消息标题中显示的异常 - 但我也收到了 Nullable 类型和其他类型的异常.当我尝试将表达式编译到函数中时抛出异常.

I am getting the exception shown in the title of this message whenever I try to access a property of type Int32 - but I am also getting it for Nullable types and others. The exception is thrown when I try to compile the expression into the function.

有人可以建议我如何在保持 Lambda 功能的同时以不同的方式处理此问题,以便我可以缓存访问器吗?

Can anybody suggest how I might go about this differently whilst maintaining the Lambda functionality so that I can cache the accessors?

推荐答案

您是否尝试过使用 表达式.转换?这将添加拳击/举重/等转换.

Have you tried using Expression.Convert? That will add the boxing/lifting/etc conversion.

Expression conversion = Expression.Convert(expression, typeof(object));
func = Expression.Lambda<Func<T, Object>>(conversion, parameterExpression).Compile();

这篇关于“System.Int32"类型的表达式不能用于返回类型“System.Object"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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