void Main()
{
var numbers = new[] { 1, 2, 3, 4, 5 };
var strings = new[] {"Hello", " ", "World" , "!"};
Console.WriteLine(MConcat<int, IntSGroup>(numbers));
Console.WriteLine(MConcat<string, StringSGroup>(strings));
}
public interface SGroup<T> // наш тайпкласс
{
public T Zero { get; }
public T Add(T x, T y);
}
public struct IntSGroup : SGroup<int> // реализации для наших типов - привет, имплиситы
{
public int Zero => 0;
public int Add(int x, int y) => x + y;
}
public struct StringSGroup : SGroup<String>
{
public string Zero => "";
public string Add(string x, string y) => x + y;
}
// пример абстрактного кода, работающего с тайпклассами
public static T MConcat<T, TGroup>(IEnumerable<T> items) where TGroup : struct, SGroup<T> {
var typeclass = default(TGroup);
return items.Aggregate(typeclass.Zero, typeclass.Add);
}