有沒有什麼方法可以用對象初始值設定器和表達式樹來創建對象的實例?我的意思是創建一個表達式樹構建這個拉姆達:用對象初始化器創建實例的表達式
// my class
public class MyObject {
public bool DisplayValue { get; set; }
}
// my lambda:
var lambda = (Func<bool, MyObject>)
(displayValue => new MyObject { DisplayValue = displayValue });
如何創建這個拉姆達與表達式樹?
UPDATE:
我tryed自己寫下面的代碼:
public static Func<bool, dynamic> Creator;
static void BuildLambda() {
var expectedType = typeof(MyObject);
var displayValueParam = Expression.Parameter(typeof(bool), "displayValue");
var ctor = Expression.New(expectedType);
var local = Expression.Parameter(expectedType, "obj");
var displayValueProperty = Expression.Property(ctor, "DisplayValue");
var returnTarget = Expression.Label(expectedType);
var returnExpression = Expression.Return(returnTarget,local, expectedType);
var returnLabel = Expression.Label(returnTarget, Expression.Default(expectedType));
var block = Expression.Block(
new[] { local },
Expression.Assign(local, ctor),
Expression.Assign(displayValueProperty, displayValueParam),
Expression.Return(Expression.Label(expectedType), local, expectedType),
returnExpression,
returnLabel
);
Creator =
Expression.Lambda<Func<bool, dynamic>>(block, displayValueParam)
.Compile();
}
但它引發以下錯誤:
Cannot jump to undefined label ''.
大家可以幫我嗎?
你能閱讀我的文章:http://www.abhisheksur.com/2010/09/use-of-expression-trees-in-lamda-c。 html來生成自己? – abhishek
感謝鏈接,它似乎是一個巨大的文章。但不幸的是,我是一個表達新人,你的文章非常重要。你能發表你的建議嗎? –