中級 › cannot be used as type parameter の原因と直し方 › パターン3
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 Blob { } 6 static void Main(string[] args) { 7 System.Console.WriteLine(IsGreater(______________________)); ^ 8 } 9 }
Program.cs(7,34): error CS0311: The type 'Program.Blob' 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.Blob' to 'System.IComparable<Program.Blob>'.
空欄を埋めてビルドを通す
IsGreaterも比較可能な型しか受け付けません。制約は実行前、コンパイル時にチェックされます。
次の問題