创建Func键同时返回参考 - 和值类型 [英] Create Func to return both reference- and value-types

查看:157
本文介绍了创建Func键同时返回参考 - 和值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法返回一个 Func键<对象> 由表达式构建如下:

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

这表达式应该返回年龄 -property这个假人 -object。问题是,因为我想返回一个 Func键<的代替 Func键<对象> INT> 我得到一个

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

ArgumentExeption:类型的表达式 System.Int32 不能被用作报税表中键入 System.Object的。 (或类似的东西,有德语版)。

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

如果我倒是选择了名称 -property不是年龄 -property相同的作品。我知道这与装箱和拆箱为 INT 做并不适用对象

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?

推荐答案

您可以使用 Expression.Convert 以整数强制转换为对象是这样的:

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

这篇关于创建Func键同时返回参考 - 和值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆