防爆$ P $类型'System.Int32的“的pssion不能用于返回类型'System.Object的' [英] Expression of type 'System.Int32' cannot be used for return type 'System.Object'

查看:225
本文介绍了防爆$ P $类型'System.Int32的“的pssion不能用于返回类型'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.

在code我到目前为止如下:......

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类型的属性的例外 - 但我也得到它的可空类型等。  当我尝试编译EX pression到功能的异常。

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.

任何人都可以建议如何我会去了解这个不同,同时保持拉姆达功能,以便我可以缓存访问?

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

推荐答案

您是否尝试过使用防爆pression.Convert ?这将增加的拳击/升降/等转换。

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();

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

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