Dies ist eine Lernübung in Ausdrucksbäumen.Wie füge ich eine Konvertierungsfunktion in meinen Ausdrucksbaum ein?
Ich habe diesen Arbeits Code:
class Foo
{
public int A { get; set; }
public string B { get; set; }
}
class Bar
{
public int C { get; set;}
public string D { get; set; }
}
class FieldMap
{
public PropertyInfo From { get; set; }
public PropertyInfo To { get; set; }
}
class Program
{
static Action<TFrom, TTo> CreateMapper<TFrom, TTo>(IEnumerable<FieldMap> fields)
{
ParameterExpression fromParm = Expression.Parameter(typeof(TFrom), "from");
ParameterExpression toParm = Expression.Parameter(typeof(TTo), "to");
//var test = new Func<string, string>(x => x);
//var conversionExpression = Expression.Call(null, test.Method);
var assignments = from fm in fields
let fromProp = Expression.Property(fromParm, fm.From)
let toProp = Expression.Property(toParm, fm.To)
select Expression.Assign(toProp, fromProp);
var lambda = Expression.Lambda<Action<TFrom, TTo>>(
Expression.Block(assignments),
new ParameterExpression[] { fromParm, toParm });
return lambda.Compile();
}
static void Main(string[] args)
{
var pa = typeof(Foo).GetProperty("A");
var pb = typeof(Foo).GetProperty("B");
var pc = typeof(Bar).GetProperty("C");
var pd = typeof(Bar).GetProperty("D");
var mapper = CreateMapper<Foo, Bar>(new FieldMap[]
{
new FieldMap() { From = pa, To = pc },
new FieldMap() { From = pb, To = pd }
});
Foo f = new Foo();
Bar b = new Bar();
f.A = 20;
f.B = "jason";
b.C = 25;
b.D = "matt";
mapper(f, b); // copies properties from f into b
}
}
gut funktioniert. Wie erwähnt, kopiert es die entsprechenden Eigenschaften von f
zu b
. Nun nehme ich an, dass ich eine Konvertierungs- oder Formatierungsmethode hinzufügen möchte, die die "from-Eigenschaft" übernimmt, einige Zauber ausführt und dann die Eigenschaft "to" gleich dem Ergebnis setzt. Beachten Sie die beiden auskommentierten Zeilen in der Mitte von CreateMapper
.
Wie bewerkstellige ich das? Ich bin so weit gekommen, aber ich bin jetzt irgendwie verloren.
Sie ein Gentleman und ein Gelehrter sind. – Amy
Err, oder eine Gentlewoman. – Amy