## “表达式树”配合“泛型参数字典”定义通用操作

2009-11-13 13:53  Jeffrey Zhao  阅读(18270)  评论(27编辑  收藏

public static class EnumerableExtensions
{
public static T Sum<T>(this IEnumerable<T> source)
{
T sum = default(T);
bool first = true;

foreach (var item in source)
{
if (first)
{
sum = item;
first = false;
}
else
{
sum += item;
}
}

return sum;
}
}

public static class AddOperation<T>
{
{
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
var lambda = Expression.Lambda<Func<T, T, T>>(add, x, y);
}

private static Func<T, T, T> s_add;

public static T Add(T x, T y)
{
}
}

public struct Complex
{
public int m_real;
public int m_imaginary;

public Complex(int real, int imaginary)
{
this.m_real = real;
this.m_imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.m_real + c2.m_real, c1.m_imaginary + c2.m_imaginary);
}

public override string ToString()
{
return (String.Format("{0} + {1}i", m_real, m_imaginary));
}
}

// 调用
AddOperation<Complex>.Add(new Complex(1, 2), new Complex(2, 3));

static AddOperation()
{
if (typeof(T) == typeof(string))
{
Func<string, string, string> strAdd = (x, y) => x + y;
}
else
{
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
var lambda = Expression.Lambda<Func<T, T, T>>(add, x, y);
}
}

public static T Sum<T>(this IEnumerable<T> source)
{
T sum = default(T);
bool first = true;

foreach (var item in source)
{
if (first)
{
sum = item;
first = false;
}
else
{
}