There are interfaces for some operations on number types, for example, IComparable<T> , IConvertible and IEquatable<T> . You can specify this to get specific functionality:
public class MaxFinder<T> where T : IComparable<T> { public T FindMax(IEnumerable<T> items) { T result = default(T); bool first = true; foreach (T item in items) { if (first) { result = item; first = false; } else { if (item.CompareTo(result) > 0) { result = item; } } } return result; } }
You can use delegates to extend the class with specific types of operations:
public class Adder<T> { public delegate T AddDelegate(T item1, T item2); public T AddAll(IEnumerable<T> items, AddDelegate add) { T result = default(T); foreach (T item in items) { result = add(result, item); } return result; } }
Using:
Adder<int> adder = new Adder<int>(); int[] list = { 1, 2, 3 }; int sum = adder.AddAll(list, delegate(int x, int y) { return x + y; });
You can also store delegates in a class and have different factory methods that set delegates for a particular data type. Thus, type code is specific only to factory methods.
Guffa Aug 12 '09 at 19:11 2009-08-12 19:11
source share