中級 › cannot be used as type parameter の原因と直し方 › パターン5
cannot be used as type parameter の原因と直し方
where T : IComparable<T>のような制約を満たさない型を、ジェネリックメソッドの型引数として渡そうとすると出るコンパイルエラーです。
1 class Program { 2 static bool IsGreater<T>(T a, T b) where T : System.IComparable<T> { 3 return a.CompareTo(b) > 0; 4 } 5 class Marker { } 6 static void Main(string[] args) { 7 System.Console.WriteLine(IsGreater(__________________________)); ^ 8 } 9 }
Program.cs(7,34): error CS0311: The type 'Program.Marker' cannot be used as type parameter 'T' in the generic type or method 'Program.IsGreater<T>(T, T)'. There is no implicit reference conversion from 'Program.Marker' to 'System.IComparable<Program.Marker>'.
空欄を埋めてビルドを通す
独自クラスにIComparable<T>の実装がなければ型引数として使えません。
次の問題