为什么一些对象属性UnaryEx pression和其他MemberEx pression?属性、对象、UnaryEx、pression

2023-09-02 01:54:24 作者:孤酒

作用于回答我的Select使用一个lambda,而不是一个字符串属性名称的问题,希望将属性添加到集合如下一个模型属性:

Acting on the answer to my Select a model property using a lambda and not a string property name question, wanting to add properties to a collection as follows:

var props = new ExportPropertyInfoCollection<JobCard>();
props.Include(model => model.BusinessInstallNumber).Title("Install No").Width(64).KeepZeroPadding(true);
props.Include(model => model.DeviceName).Title("Device").Width(70);
props.Include(model => model.DateRequested).Title("Request Date").Format("{0:dd/MM/yyyy}").Width(83);

我写了下面的code中的包含方法:

public class PropertyCollection<T>
{
    public void Include(Expression<Func<T, object>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression != null)
        {
            var pes = new ExportPropertyInfoBuilder {Property = new ExportPropertyInfo {Property = memberExpression.Member as PropertyInfo}};
            Properties.Add(pes.Property.Property.Name, pes.Property);
            return pes;
    }

但是,在运行的code,我发现了一些lambda表达式产生的 MemberEx pression 作为预期值,但其他人得到的 UnaryEx pression 值。我不得不为code中的第一行更改为以下之前,我可以添加使用lambda表达式我的所有属性:

However, on running the code, I found some of the lambdas yielded MemberExpression values as expected, but others yielded UnaryExpression values. I had to change the first line of code to the following before I could add all my properties using lambdas:

var memberExpression = expression.Body as MemberExpression ?? ((UnaryExpression) expression.Body).Operand as MemberExpression;

所有的属性是简单类型,即字符串,日期时间,整型,布尔等,在POCO业务对象。他们都装饰有几种不同的的DataAnnotations 属性。

是什么原因导致了一些在我的例子中,lambda表达式产生的 MemberEx pression 值和其他 UnaryEx pression 值?在我的例子,第一个 UnaryEx pression 在第三行,在日期时间属性,但是布尔特性也导致 UnaryEx pressions

What causes some of the lambdas in my example to yield MemberExpression values and others UnaryExpression values? In my example, the first UnaryExpression is on the third line, the DateTime property, but boolean properties also result in UnaryExpressions.

推荐答案

我想我知道是什么问题。你的前pression收益型对象

I think I know what the problem is. Your expression returns type object.

如果您更改为防爆pression&LT; Func键&LT; T,R&GT;&GT; 的返回类型应正确推断和 UnaryEx pression (我会承担一定的装箱操作)不应该发生。

If you change this to Expression<Func<T, R>> the return type should be correctly inferred, and UnaryExpression (which I will assume is some boxing operation) should not occur.

更新:

有关签名包含应该是:

public void Include<T, R>(Expression<Func<T, R>> expression)