为什么不能防爆pression的身体在C#.NET不使用int类型,双或布尔的属性? [英] Why could an Expression's Body in C#.net not use properties of type int, double or bool?

查看:163
本文介绍了为什么不能防爆pression的身体在C#.NET不使用int类型,双或布尔的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数:

private string GetPropertyName(Expression<Func<object, object>> f) {
    if ((f.Body as MemberExpression) != null) {
        return (f.Body as MemberExpression).Member.Name;
    }
    return "";
}

和使用它是这样的:

string x1 = GetPropertyName(x => Property1);
string x2 = GetPropertyName(x => Property2);
string x3 = GetPropertyName(x => Property3);

在这里Property1是int,Property2是一个字符串,Property3是一个对象...

where Property1 is an int, Property2 is a string, and Property3 is an object...

只有名称和对象恭敬地正确返回,但Property1的f.Body为MemberEx pression为空...

Only the names of Property2 and Property3 of types string and object respectfully are correctly returned, but Property1's f.Body as MemberExpression is null...

为什么会这样,以及我们如何改变code,因此函数正确返回属性的名字?

Why is this so, and how can we change the code so the function returns the Properties' names correctly?

推荐答案

我想问题是, X =&GT; Property1 EX pression包含隐式转换为对象。 编译器增加了这样的投履行getPropertyName方法的参数。

I guess the problem is that x => Property1 expression contains implicit cast to object. Compiler adds such cast to fulfil arguments of GetPropertyName.

您应该检查该投

private string GetPropertyName(Expression<Func<object, object>> f) {
    var body = f.Body;
    if (body.NodeType==ExpressionType.Convert)
      body = ((UnaryExpression) body).Operand;
    if ((body as MemberExpression) != null) {
        return (body as MemberExpression).Member.Name;
    }
    return "";
}

这篇关于为什么不能防爆pression的身体在C#.NET不使用int类型,双或布尔的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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