Create Func to return both reference- and value-types

断了今生、忘了曾经 提交于 2019-12-04 03:43:43

问题


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:


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


来源:https://stackoverflow.com/questions/34811468/create-func-to-return-both-reference-and-value-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!