public class UserEntity { public string Id { get; set; } public string Account { get; set; } public string Name { get; set; } public string Pwd { get; set; } public DateTime? Birthday { get; set; } public string Theme { get; set; } } static void DO1() { UserEntity user = new UserEntity { Id = "afdsafdsafdasfd", Account = "233322", Name = "FFFFF", Pwd = "sfaf", Birthday = DateTime.Now, Theme = "111" }; Action<UserEntity> action = u => new UserEntity { Id = user.Id, Account = user.Account }; }
Action<T>赋值都要每个属性写过去,我现在想把user所有属性值都给Action,有啥好办法吗?
public void Edit(Expression<Func<UserEntity, bool>> predicate, Expression<Action<UserEntity>> updateAction)
确实有比较懒得方法
这个是对象映射问题
public static Func<TIn, TOut> GetMappingFunc<TIn, TOut>(this TIn objin)
{
ParameterExpression input = Expression.Parameter(typeof(TIn), "p");
List<MemberBinding> memberBindings = new List<MemberBinding>();
//绑定属性
PropertyInfo[] outPropertyInfos = typeof(TOut).GetProperties();
foreach (var prop in outPropertyInfos)
{
PropertyInfo inPropertyInfo = typeof(TIn).GetProperty(prop.Name);
if (inPropertyInfo != null)
{
MemberExpression property = Expression.Property(input, inPropertyInfo);
MemberBinding memberBinding = Expression.Bind(prop, property);
memberBindings.Add(memberBinding);
}
}
//绑定字段
FieldInfo[] outFieldInfos = typeof(TOut).GetFields();
foreach (var field in outFieldInfos)
{
FieldInfo inFieldInfo = typeof(TIn).GetField(field.Name);
if (inFieldInfo != null)
{
MemberExpression fieldInfo = Expression.Field(input, inFieldInfo);
MemberBinding memberBinding = Expression.Bind(field, fieldInfo);
memberBindings.Add(memberBinding);
}
}
MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindings.ToArray());
Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(init, input);
Func<TIn, TOut> func = lambda.Compile();
return func;
}
用法
Func<UserEntity, UserEntity> func = user.GetMappingFunc<UserEntity, UserEntity>();
Action<UserEntity> action = u =>func(user);
可以用来进行子类和父类的相互映射
这个委托你想用来干什么,只是复制一遍user吗,下一步干什么?
提交给数据库修改实体
@happydaily: 看的有点莫名其妙。。。。类型一样的,你直接传对象就好了
如果说要在action内部做其他处理并且和数据库字段对应,考虑反射
不太确定你的需求
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Program p=new Program();
Action<Program> action = SayHello;
}
public static void SayHello(Program str)
{
Console.WriteLine(str.ToString());
}
}
你的问题是不是说在sayhello里转换成为数据库的值?如果列名一致,可以用反射。
不一致可以考虑automaper之类的。