Create Func to return both reference- and value-ty

2019-02-24 10:20发布

I have a method returning a Func<object> built 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 Foo-object. The problem is that as I want to return a Func<object> instead of a Func<int> I get an

ArgumentException: An expression of type System.Int32 cannot be used as return-type System.Object. (or something similar, have german version).

If I´d chose the Name-property instead of the Age-property the same works. I know this has to do with boxing and unboxing as int does not extend object.

However how may I return the appropriate function that represents a value-type-property?

1条回答
smile是对你的礼貌
2楼-- · 2019-02-24 10:48

You can use Expression.Convert to cast the integer to an object like this:

var expr = Expression.Convert(
    Expression.Property(
        Expression.Constant(
            new Foo {Name = "Hans", Age = 3},
            typeof (Foo)),
        "Age"),
    typeof(object));
查看更多
登录 后发表回答