Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

.net - Why are some object properties UnaryExpression and others MemberExpression?

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

I wrote the following code in the Include method:

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

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;

All the properties are 'simple' types, i.e. string, DateTime, int, bool, etc. in a POCO business object. They are decorated with several varying DataAnnotations attributes.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.

Update:

The signature for Include should be:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...