如果您使用的是.Net 4,則可以使用新的Expression
類型(已添加以支持dynamic
),以創建表達式來分配屬性,將其編譯爲委託,並重復調用該表達式。性能應該與使用Reflection.Emit相媲美。
class ObjectFiller<T>
{
private static Func<IDictionary<string, object>, T> FillerDelegate;
private static void Init()
{
var obj = Expression.Parameter(typeof(T), "obj");
var valuesDictionary = Expression.Parameter(typeof(IDictionary<string, object>), "values");
var create = Expression.Assign(
obj, Expression.Call(typeof(Activator), "CreateInstance", new[] { typeof(T) }));
var properties = typeof(T).GetProperties();
var setters = Expression.Block(properties.Select(p => CreateSetter(p, obj, valuesDictionary)));
var methodBody = Expression.Block(typeof(T), new[] { obj }, create, setters, obj);
var fillerExpression = Expression.Lambda<Func<IDictionary<string, object>, T>>(methodBody, valuesDictionary);
FillerDelegate = fillerExpression.Compile();
}
static Expression CreateSetter(PropertyInfo property, Expression obj, Expression valuesDictionary)
{
var indexer = Expression.MakeIndex(
valuesDictionary,
typeof(IDictionary<string, object>).GetProperty("Item", new[] { typeof(string) }),
new[] { Expression.Constant(property.Name) });
var setter = Expression.Assign(
Expression.Property(obj, property),
Expression.Convert(indexer, property.PropertyType));
var valuesContainsProperty = Expression.Call(
valuesDictionary, "ContainsKey", null, Expression.Constant(property.Name));
var condition = Expression.IfThen(valuesContainsProperty, setter);
return condition;
}
public T FillObject(IDictionary<string, object> values)
{
if (FillerDelegate == null)
Init();
return FillerDelegate(values);
}
}
你可以做的.Net 3非常相似的東西太多,使用Expression
版本對象初始化的。
我以前沒見過。井井有條。 –
謝謝Marc,最好的解決方案。 – Argons