這裏我變種
使用二進制運算符類型T作爲默認的「添加」,
但提供定製的附加功能對於一些特定類型,並使用默認的二進制文件添加僅剩下
能力(如果二進制加法沒有爲類型T定義,則在運行時拋出一個異常)。
private static Func<T, T, T> CreateAdd<T>()
{
Func<T, T, T> addMethod = null;
Expression<Func<T, T, T>> addExpr = null;
if (typeof(T) == typeof(string))
{
//addExpr = (Expression<Func<T, T, T>>)((a, b) => ((T)(object)((string)(object)a + (string)(object)b)));
//addMethod = addExpr.Compile();
addMethod = (a, b) => {
string aa = (string)(object)a;
string bb = (string)(object)b;
double da;
double db;
double.TryParse(aa, out da);
double.TryParse(bb, out db);
double c = da + db;
string res = c.ToString();
return (T)(object)res;
}; // End Delegate addMethod
}
else
{
ParameterExpression lhs = Expression.Parameter(typeof(T), "lhs");
ParameterExpression rhs = Expression.Parameter(typeof(T), "rhs");
addExpr = Expression<Func<T, T, T>>.Lambda<Func<T, T, T>>(
Expression.Add(lhs, rhs),
new ParameterExpression[] { lhs, rhs }
);
addMethod = addExpr.Compile();
}
return addMethod;
}
// MvcTools.Aggregate.Functions.Sum<T>(vals);
public static T Sum<T>(params T[] vals)
{
T total = default(T);
//Enumerable.Aggregate(vals, delegate(T left, T right) { return left + right; });
Func<T, T, T> addMethod = CreateAdd<T>();
foreach (T val in vals)
{
total = addMethod(total, val);
}
return total;
} // End Function Sum
例子:
int[] vals = new int[] { 1, 2, 3, 4, 5 };
int sum = MvcTools.Aggregate.Functions.Sum<int>(vals);
double[] dvals = new double[] { 1, 2, 3, 4, 5 };
double dsum = MvcTools.Aggregate.Functions.Sum<double>(dvals);
string[] strs = new string[] { "1", "2", "3", "4", "5" };
string str = MvcTools.Aggregate.Functions.Sum<string>(strs);
輸出:15,15.0 「15」
非常優雅,但缺乏定製+爲X型,雖然這可以很容易地完成工作的能力。添加了我的變體;)不知道哪個更快;) – 2013-04-20 23:15:59