How set value a property selector Expression>

前端 未结 6 683
野趣味
野趣味 2020-11-30 04:32

i need associate a entity property Address in my Person class entity with expressions linq in my FactoryEntities class using pattern factory idea, look this is what I have a

6条回答
  •  感动是毒
    2020-11-30 05:25

    You can set the property like this:

    public void AssociateWithEntity(
        Expression> entityExpression,
        TProperty newValueEntity)
        where TProperty : Entity
    {
        if (instanceEntity == null)
            throw new ArgumentNullException();
    
        var memberExpression = (MemberExpression)entityExpression.Body;
        var property = (PropertyInfo)memberExpression.Member;
    
        property.SetValue(instanceEntity, newValueEntity, null);
    }
    

    This will work only for properties, not fields, although adding support for fields should be easy.

    But the code you have for getting the person won't work. If you want to keep the void return type of AssociateWithEntity(), you could do it like this:

    var factory = new FactoryEntity();
    factory.AssociateWithEntity(p => p.Address, address);
    Person person = factory.InstanceEntity;
    

    Another option is a fluent interface:

    Person person = new FactoryEntity()
        .AssociateWithEntity(p => p.Address, address)
        .InstanceEntity;
    

提交回复
热议问题