gpt4 book ai didi

c# - 如何设置属性选择器的值 Expression>

转载 作者:IT王子 更新时间:2023-10-29 04:24:14 24 4
gpt4 key购买 nike

我需要使用模式工厂的想法将我的 Person 类实体中的实体属性地址与我的 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*/
}
}

最佳答案

这有效:

以下辅助方法将 getter 表达式转换为 setter 委托(delegate)。如果你想返回 Expression<Action<T,TProperty>>而不是 Action<T,TProperty> ,只是不要调用 Compile()方法在最后。

注:代码来自Ian Mercer的博客:http://blog.abodit.com/2011/09/convert-a-property-getter-to-a-setter/

    /// <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();
}

关于c# - 如何设置属性选择器的值 Expression<Func<T,TResult>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com