相關:
我想使用Expression Tree
為新類創建Selector
表達式。請考慮以下代碼:
s => new Allocation
{
Id = s.Id,
UnitName = s.UnitName,
Address = s.NewAddress,
Tel = s.NewTel
}
我有一個大類( MyClass
),我想選擇它的一些屬性。但我想動態創建它。我怎麼能這樣做?
謝謝
解決這個問題的方法是編寫等效代碼,然後對其進行反編譯。例如:
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
ShowMeTheLambda<Foo, Allocation>(s => new Allocation
{
Id = s.Id,
UnitName = s.UnitName,
Address = s.NewAddress,
Tel = s.NewTel
});
}
static void ShowMeTheLambda<TFrom, TTo>(Expression<Func<TFrom, TTo>> lambda)
{ }
}
class Foo
{
public int Id { get; set; }
public string UnitName { get; set; }
public string NewTel { get; set; }
public string NewAddress { get; set; }
}
class Allocation
{
public int Id { get; set; }
public string UnitName { get; set; }
public string Tel { get; set; }
public string Address { get; set; }
}
現在,如果我編譯它並用“反射器”反編譯它,我得到:
private static void Main()
{
ParameterExpression expression;
MemberBinding[] bindings = new MemberBinding[] { Expression.Bind((MethodInfo) methodof(Allocation.set_Id), Expression.Property(expression = Expression.Parameter(typeof(Foo), "s"), (MethodInfo) methodof(Foo.get_Id))), Expression.Bind((MethodInfo) methodof(Allocation.set_UnitName), Expression.Property(expression, (MethodInfo) methodof(Foo.get_UnitName))), Expression.Bind((MethodInfo) methodof(Allocation.set_Address), Expression.Property(expression, (MethodInfo) methodof(Foo.get_NewAddress))), Expression.Bind((MethodInfo) methodof(Allocation.set_Tel), Expression.Property(expression, (MethodInfo) methodof(Foo.get_NewTel))) };
ParameterExpression[] parameters = new ParameterExpression[] { expression };
ShowMeTheLambda<Foo, Allocation>(Expression.Lambda<Func<Foo, Allocation>>(Expression.MemberInit(Expression.New(typeof(Allocation)), bindings), parameters));
}
注意: memberof
和methodof
實際上並不存在於C#中 - 您可以通過反射手動獲取方法信息,也可以使用Expression.PropertyOrField
。因此我們可以將其重寫為:
ParameterExpression expression = Expression.Parameter(typeof(Foo), "s");
MemberBinding[] bindings = new MemberBinding[]
{
Expression.Bind(typeof(Allocation).GetProperty(nameof(Allocation.Id)), Expression.PropertyOrField(expression, nameof(Foo.Id))),
Expression.Bind(typeof(Allocation).GetProperty(nameof(Allocation.UnitName)), Expression.PropertyOrField(expression, nameof(Foo.UnitName))),
Expression.Bind(typeof(Allocation).GetProperty(nameof(Allocation.Address)), Expression.PropertyOrField(expression, nameof(Foo.NewAddress))),
Expression.Bind(typeof(Allocation).GetProperty(nameof(Allocation.Tel)), Expression.PropertyOrField(expression, nameof(Foo.NewTel))),
};
ParameterExpression[] parameters = new ParameterExpression[] { expression };
var lambda = Expression.Lambda<Func<Foo, Allocation>>(Expression.MemberInit(Expression.New(typeof(Allocation)), bindings), parameters);