繁体   English   中英

类型'System.Int32'的表达式不能用于返回类型'System.Object'

[英]Expression of type 'System.Int32' cannot be used for return type 'System.Object'

我正在尝试生成一个简单的脚本系统,用于打印标签。 我在过去做过这个没有问题的反射,但我现在正在尝试使用Lambda函数,以便我可以缓存函数以便重用。

我到目前为止的代码如下......

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;

    }

}

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

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

任何人都可以建议我在保持Lambda功能的同时以不同的方式解决这个问题,以便我可以缓存访问器吗?

你尝试过使用Expression.Convert吗? 这将添加拳击/提升/等转换。

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

我希望这段代码可以帮到你

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Student
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Student();
            PrintProperty(a, "Name");
            PrintProperty(a, "Age");
            Console.ReadKey();

        }
        private static void PrintProperty<T>(T a, string propName)
        {
            PrintProperty<T, object>(a, propName);
        }
        private static void PrintProperty<T, TProperty>(T a, string propName)
        {
            ParameterExpression ep = Expression.Parameter(typeof(T), "x");
            MemberExpression em = Expression.Property(ep, typeof(T).GetProperty(propName));
            var el = Expression.Lambda<Func<T, TProperty>>(Expression.Convert(em, typeof(object)), ep);
            Console.WriteLine(GetValue(a, el));
        }

        private static TPorperty GetValue<T, TPorperty>(T v, Expression<Func<T, TPorperty>> expression)
        {
            return expression.Compile().Invoke(v);
        }

        public class Student
        {
            public Student()
            {
                Name = "Albert Einstein";
                Age = 15;
            }
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM