От: | Sinclair | https://github.com/evilguest/ | |
Дата: | 10.06.20 02:47 | ||
Оценка: |
S>public shape SGroup<T>
S>{
S> static T operator +(T t1, T t2);
S> static T Zero {get;}
S>}
S>
S>This declaration says that a type can be an SGroup<T> if it implements a+ operator over T, and a Zero static property.
S>public extension IntGroup of int: SGroup<int>
S>{
S> public static int Zero => 0;
S>}
S>
S>And the extension.
S>public static AddAll<T>(T[] ts) where T: SGroup<T> // shape used as constraint
S>{
S> var result = T.Zero; // Making use of the shape's Zero property
S> foreach (var t in ts) { result += t; } // Making use of the shape's + operator
S> return result;
S>}
S>
S>int[] numbers = { 5, 1, 9, 2, 3, 10, 8, 4, 7, 6 };
S>WriteLine(AddAll(numbers)); // infers T = int
S>
S> public shape SGroup<T>
S>
S>public extension IntGroup of int: SGroup<int>
S>
S>role IntGroup extednds int
S>
S>public static int Zero => 0;
S>