Genericsへの不満
概ね好印象なC#2.0ですが、Genericsでちょっとイマイチなところがあります。C++のテンプレートのサンプルにありそうな例ですが、C#では、これが出来ません。
#region Using directives
using System;
using System.Collections.Generic;
#endregion
namespace ConsoleApplication1
{
class Program
{
static T Method<T>(T ts)
{
T sum = default(T);
foreach (T t in ts)
sum += t; // Operator '+=' cannot be applied to operands of type 'T' and 'T'
return sum;
}
static void Main(string args)
{
Console.WriteLine(Program.Method<int>(new int[] { 1, 2, 3 }));
Console.ReadLine();
}
}
}
型パラメータTにはoperator+=が無いからなのですが、operatorはインタフェースでもなんでも無いため、operatorをサポートする型というのを指定する方法がありません。色々議論があったようですが、結局のところプリミティブ型に対するGenericなアルゴリズムは書けない方向らしい。がーん。Nullable Typeよりこっちのほうがよっぽど使うと思うんだけど・・・