至於我明白你的問題,你可以做到這一點使用表達式:
/// <summary>
/// A class with many-many properties
/// </summary>
class MyClass
{
public Decimal A { get; set; }
public Decimal B { get; set; }
public Decimal C { get; set; }
}
class PropertyHelper<T, TProperty>
{
private readonly Func<T, TProperty> selector;
private readonly Action<T, TProperty> setter;
public PropertyHelper(Func<T, TProperty> selector, Action<T, TProperty> setter)
{
this.selector = selector;
this.setter = setter;
}
public Func<T, TProperty> Selector
{
get { return selector; }
}
public Action<T, TProperty> Setter
{
get { return setter; }
}
}
class AggregateHelper<T, TProperty>
{
private readonly Dictionary<PropertyInfo, PropertyHelper<T, TProperty>> helpers;
public AggregateHelper()
{
this.helpers = typeof(T)
.GetProperties()
.Where(p => p.PropertyType == typeof(TProperty))
.ToDictionary(p => p, p => new PropertyHelper<T, TProperty>(MakeSelector(p), MakeSetter(p)));
}
private Func<T, TProperty> MakeSelector(PropertyInfo property)
{
var parameterExpr = Expression.Parameter(typeof(T));
var lambda = (Expression<Func<T, TProperty>>)Expression.Lambda(
Expression.Property(parameterExpr, property), parameterExpr);
return lambda.Compile();
}
private Action<T, TProperty> MakeSetter(PropertyInfo property)
{
var instanceExpr = Expression.Parameter(typeof(T));
var parameterValueExpr = Expression.Parameter(typeof(TProperty));
var lambda = (Expression<Action<T, TProperty>>)Expression.Lambda(
Expression.Call(instanceExpr, property.GetSetMethod(), parameterValueExpr),
instanceExpr,
parameterValueExpr);
return lambda.Compile();
}
public IEnumerable<PropertyInfo> Properties
{
get { return helpers.Keys; }
}
public PropertyHelper<T, TProperty> this[PropertyInfo property]
{
get { return helpers[property]; }
}
}
用法:
public static void Do()
{
var target = new MyClass();
var list = new List<MyClass>
{
new MyClass { A = 1M, B = 2M, C = 3M },
new MyClass { A = 10M, B = 20M, C = 30M },
new MyClass { A = 100M, B = 200M, C = 300M }
};
// calculate 'min' for all decimal properties
var helper = new AggregateHelper<MyClass, Decimal>();
foreach (var property in helper.Properties)
{
var propertyHelper = helper[property];
propertyHelper.Setter(target, list.Min(propertyHelper.Selector));
}
}
編譯lambda表達式工作得更快,然後反思,就沒有拳擊/拆箱。
是否屬於同一類型的所有屬性? – Botz3000
不,有些是字符串,但那不是主要問題,我可以隨時檢查,所以屬性是一個int,但我應該如何寫入來設置屬性? – Fore
所以,你想要一個新的對象,在每個屬性中包含所有其他對象的這個屬性的平均值? – phg