Create Func to Return Both Reference and Values

I have a method that returns Func<object>created by an expression as follows:

var expr = Expression.Property(
        Expressions.Expression.Constant(new Foo { Name = "Hans", Age = 3 }, typeof(Foo)), 
        "Age");
var f = Expression.Lambda<Func<object>>(expr).Compile();

This expression should return the Age-property of this dummy Fooobject. The problem is that since I want to return Func<object>instead Func<int>, I get

ArgumentException: a type expression System.Int32cannot be used as a return type System.Object. (or something similar, have a German version).

If I chose Name-property instead of Age-property, then the same thing works. I know that this is due to boxing and unboxing, as it intdoes not expand object.

However, how can I return the corresponding function that represents the value-type property?

+4
source share
1 answer

You can use Expression.Convertto distinguish an integer with the objectfollowing:

var expr = Expression.Convert(
    Expression.Property(
        Expression.Constant(
            new Foo {Name = "Hans", Age = 3},
            typeof (Foo)),
        "Age"),
    typeof(object));
+4
source

Source: https://habr.com/ru/post/1624432/


All Articles