انجام اعمال ریاضی بر روی Generics
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۴/۰۱ ۰:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public interface ICalculator<T>
{
T Add(T operand1, T operand2);
}
public class Calculator<T> : ICalculator<T>
{
public T Add(T operand1, T operand2)
{
return operand1 + operand2;
}
} Operator '+' cannot be applied to operands of type 'T' and 'T'
public class Calculator2<T>
{
public T Sum(List<T> list)
{
T sum = 0;
for (int i = 0; i < list.Count; i++)
sum += list[i];
return sum;
}
} public interface ICalculator<T>
{
T Add(T operand1, T operand2);
}
public class Int32Calculator : ICalculator<int>
{
public int Add(int operand1, int operand2)
{
return operand1 + operand2;
}
}
public class AlgorithmLibrary<T> where T : new()
{
private readonly ICalculator<T> _calculator;
public AlgorithmLibrary(ICalculator<T> calculator)
{
_calculator = calculator;
}
public T Sum(List<T> items)
{
var sum = new T();
for (var i = 0; i < items.Count; i++)
{
sum = _calculator.Add(sum, items[i]);
}
return sum;
}
} var result = new AlgorithmLibrary<int>(new Int32Calculator()).Sum(new List<int> { 1, 2, 3 }); public class Algorithms<T> where T : new()
{
public T Calculate(Func<T, T, T> add, IEnumerable<T> numbers)
{
var sum = new T();
foreach (var number in numbers)
{
sum = add(sum, number);
}
return sum;
}
} var result = new Algorithms<int>().Calculate((a, b) => a + b, new[] { 1, 2, 3 }); public class Calculator<T> : ICalculator<T>
{
public T Add(T operand1, T operand2)
{
return (dynamic)operand1 + operand2;
}
} var test = new Calculator<int>().Add(1, 2);
public T Add(T t1, T t2)
{
if (typeof(T) == typeof(double))
{
var d1 = (double)t1;
var d2 = (double)t2;
return (T)(d1 + d2);
}
else if (typeof(T) == typeof(int)){
var i1 = (int)t1;
var i2 = (int)t2;
return (T)(i1 + i2);
}
else ...
} using System;
using System.Linq.Expressions;
namespace GenericsArithmetic
{
public class Solution3
{
public T Add<T>(T a, T b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T), "b");
var body = Expression.Add(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
}
} public static T Sum<T>(this IEnumerable<T> source)
{
T sum = Operator<T>.Zero;
foreach (T value in source)
{
sum = Operator.Add(sum, value);
}
return sum;
}