C# “System.Int32”类型的表达式不能用于返回类型“System.Object”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2200209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:19:24  来源:igfitidea点击:

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

c#.netlambda

提问by Martin Robins

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.

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

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.

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

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.

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

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

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

采纳答案by Jon Skeet

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

您是否尝试过使用Expression.Convert?这将添加拳击/举重/等转换。

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

回答by Zekaee Esmaeel

I hope this code will help you ?

我希望这段代码对你有帮助?

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; }
        }
    }
}