linq 如何设置属性选择器的值表达式< Func< T,TResult>>

nzrxty8p  于 11个月前  发布在  其他
关注(0)|答案(8)|浏览(130)

我需要将Person类实体中的实体属性Address与FactoryEntities类中的表达式linq关联起来,使用模式工厂的想法,看,这是我拥有的,我想做的:

Address address = new Address();
address.Country = "Chile";
address.City = "Santiago";
address.ZipCode = "43532";
//Factory instance creation object
//This is idea
Person person = new FactoryEntity<Person>().AssociateWithEntity(p=>p.Address, address);

public class Person: Entity
{
    public string Name{ get; set; }
    public string LastName{ get; set; }
    public Address Address{ get; set; }
}

public class Address: Entity
{
    public string Country{ get; set; }
    public string City{ get; set; }
    public string ZipCode{ get; set; }
}

public class FactoryEntity<TEntity> where TEntity : Entity
{
    public void AssociateWithEntity<TProperty>(Expression<Func<TEntity, TProperty>> entityExpression, TProperty newValueEntity) where TProperty : Entity
    {
        if (instanceEntity == null || instanceEntity.IsTransient())
            throw new ArgumentNullException();

        /*TODO: Logic the association and validation 
        How set the newValueEntity into the property of entityExpression (x=>x.Direccion = direccion*/
    }
}

字符串

uqjltbpv

uqjltbpv1#

这个可以用:

下面的helper方法将getter表达式转换为setter委托。如果你想返回一个Expression<Action<T,TProperty>>而不是Action<T,TProperty>,只要在最后不调用Compile()方法就行了。

/// <summary>
    /// Convert a lambda expression for a getter into a setter
    /// </summary>
    public static Action<T, TProperty> GetSetter<T, TProperty>(Expression<Func<T, TProperty>> expression)
    {
        var memberExpression = (MemberExpression)expression.Body;
        var property = (PropertyInfo)memberExpression.Member;
        var setMethod = property.GetSetMethod();

        var parameterT = Expression.Parameter(typeof(T), "x");
        var parameterTProperty = Expression.Parameter(typeof(TProperty), "y");

        var newExpression =
            Expression.Lambda<Action<T, TProperty>>(
                Expression.Call(parameterT, setMethod, parameterTProperty),
                parameterT,
                parameterTProperty
            );

        return newExpression.Compile();
    }

字符串

vktxenjb

vktxenjb2#

你可以像这样设置属性:

public void AssociateWithEntity<TProperty>(
    Expression<Func<TEntity, TProperty>> 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);
}

字符串
这只对属性有效,而对字段无效,尽管添加对字段的支持应该很容易。
但是你用来获取person的代码将无法工作。如果你想保持AssociateWithEntity()的返回类型void,你可以这样做:

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


另一个选择是流畅的界面:

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

iaqfqrcu

iaqfqrcu3#

另一种解决方案是获取属性所有者并使用反射调用属性设置器。这种解决方案的优点是它不使用扩展方法,并且可以用任何类型调用。

private void SetPropertyValue(Expression<Func<object, object>> lambda, object value)
{
  var memberExpression = (MemberExpression)lambda.Body;
  var propertyInfo = (PropertyInfo)memberExpression.Member;
  var propertyOwnerExpression = (MemberExpression)memberExpression.Expression;
  var propertyOwner = Expression.Lambda(propertyOwnerExpression).Compile().DynamicInvoke();    
  propertyInfo.SetValue(propertyOwner, value, null);            
}
...
SetPropertyValue(s => myStuff.MyPropy, newValue);

字符串

0vvn1miw

0vvn1miw4#

这就是我的想法,我用这段代码为我工作,考虑到svick的贡献:

public class FactoryEntity<TEntity> where TEntity : Entity, new()

{

private TEntity _Entity;

    public FactoryEntity()
    {
        _Entity = new TEntity();
    }

public TEntity Build()
    {
        if (_Entity.IsValid())
            throw new Exception("_Entity.Id");

        return _Entity;
    }

public FactoryEntity<TEntity> AssociateWithEntity<TProperty>(Expression<Func<TEntity, TProperty>> foreignEntity, TProperty instanceEntity) where TProperty : Entity
    {
        if (instanceEntity == null || instanceEntity.IsTransient())
            throw new ArgumentNullException();

        SetObjectValue<TEntity, TProperty>(_Entity, foreignEntity, instanceEntity);
        return this;
    }

private void SetObjectValue<T, TResult>(object target, Expression<Func<T, TResult>> expression, TResult value)
    {
        var memberExpression = (MemberExpression)expression.Body;
        var propertyInfo = (PropertyInfo)memberExpression.Member;
        var newValue = Convert.ChangeType(value, value.GetType());
        propertyInfo.SetValue(target, newValue, null);
    }
}

字符串
在这里,我调用工厂来构建Person对象,

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


但我不知道这段代码是否是最优的,至少我没有调用compile()方法,这说明了什么?
谢谢

kknvjkwl

kknvjkwl5#

我做了混合Rytis I解决方案和https://stackoverflow.com/a/12423256/254109

private static void SetPropertyValue<T>(Expression<Func<T>> lambda, object value)
    {
        var memberExpression = (MemberExpression)lambda.Body;
        var propertyInfo = (PropertyInfo)memberExpression.Member;
        var propertyOwnerExpression = (MemberExpression)memberExpression.Expression;
        var propertyOwner = Expression.Lambda(propertyOwnerExpression).Compile().DynamicInvoke();

        propertyInfo.SetValue(propertyOwner, value, null);
    }

字符串
并称之为

SetPropertyValue(() => myStuff.MyProp, newValue);

qni6mghb

qni6mghb6#

一切都简单得多:

public static Action<T, TValue> GetSetter<T, TValue>(
    Expression<Func<T, TValue>> expression)
{
    var parameter = Expression.Parameter(typeof(TValue), "value");
    var setterLambda = Expression.Lambda<Action<T, TValue>>(
        Expression.Assign(expression.Body, parameter),
        expression.Parameters[0],
        parameter);

    return setterLambda.Compile();
}

字符串

yfjy0ee7

yfjy0ee77#

使用ExpressionVisitor,它将遍历树中的嵌套项:

var t = new SauceObject();

t.UpdateValueAndTrack(t => t.NestedProperty.Field1, "newvalue");

Console.WriteLine(t.NestedProperty.Field1);

public static void UpdateValueAndTrack<TSourceObject, TSetValue>(this TSourceObject sourceObject, Expression<Func<TSourceObject, TSetValue>> sourceExpression, TSetValue sourceValue)
{
    var t = new UpdateValueVisitor(sourceValue);
    var modifiedExpression = (Expression<Func<TSourceObject, TSetValue>>)t.Visit(sourceExpression);

    // Compile and execute the modified expression
    var modifiedFunc = modifiedExpression.Compile();
    modifiedFunc(sourceObject);
}    
public class SauceObject
{
public NestedProperty NestedProperty { get; set; } = new NestedProperty();
}

public class NestedProperty
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}

public class UpdateValueVisitor : ExpressionVisitor
{
private readonly object newValue;
private bool foundMember = false;

public UpdateValueVisitor(object newValue)
{
    this.newValue = newValue;
}

protected override Expression VisitMember(MemberExpression node)
{
    if (!foundMember && node.Member is System.Reflection.PropertyInfo propertyInfo)
    {
        // Update property
        var newValueExpression = Expression.Constant(newValue, propertyInfo.PropertyType);
        var assignment = Expression.Assign(node, newValueExpression);
        foundMember = true;
        return assignment;
    }

    return base.VisitMember(node);
}
}

字符串

gywdnpxw

gywdnpxw8#

// optionally or additionally put in a class<T> to capture the object type once
// and then you don't have to repeat it if you have a lot of properties
public Action<T, TProperty> GetSetter<T, TProperty>(
   Expression<Func<T, TProperty>> exp
) {
   var parameterExp1 = Expression.Parameter(typeof(T));
   var parameterExp2 = Expression.Parameter(typeof(TProperty));

   // turning an expression body into a PropertyInfo is common enough
   // that it's a good idea to extract this to a reusable method
   var memberExp = (MemberExpression)exp.Body;
   var propertyInfo = (PropertyInfo)memberExp.Member;

   // use the PropertyInfo to make a property expression
   // for the first parameter (the object)
   var propertyExp = Expression.Property(parameter1, propertyInfo);

   // assignment expression that assigns the second parameter (value) to the property
   var assignmentExp = Expression.Assign(propertyExp, parameterExp2);

   // then just build the lambda, which takes 2 parameters, and has the assignment
   // expression for its body
   var setterExp = Expression.Lambda<Action<T, TProperty>>(
      assignmentExp,
      parameterExp1,
      parameterExp2
   );

   return setterExp.Compile();
}

字符串
你可以做的另一件事是封装它们:

public sealed class StrongProperty<TObject, TProperty> {
   readonly PropertyInfo mPropertyInfo;

   public string Name => mPropertyInfo.Name;
   public Func<TObject, TProperty> Get { get; }
   public Action<TObject, TProperty> Set { get; }
   // maybe other useful properties

   internal StrongProperty(
      PropertyInfo propertyInfo,
      Func<TObject, TProperty> getter,
      Action<TObject, TProperty> setter
   ) {
      mPropertyInfo = propertyInfo;
      Get = getter;
      Set = setter;
   }
}


现在你可以像委托一样传递这些属性,并编写其逻辑可以随属性而变化的代码,这样就避免了不能通过引用传递属性的事实。

相关问题