Code Fix

中級cannot be used as type parameter の原因と直し方 › パターン2

cannot be used as type parameter の原因と直し方

where T : IComparable<T>のような制約を満たさない型を、ジェネリックメソッドの型引数として渡そうとすると出るコンパイルエラーです。

 1  class Program {
 2      static T Clamp<T>(T value, T min, T max) where T : System.IComparable<T> {
 3          if (value.CompareTo(min) < 0) return min;
 4          if (value.CompareTo(max) > 0) return max;
 5          return value;
 6      }
 7      class Tag { }
 8      static void Main(string[] args) {
 9          System.Console.WriteLine(Clamp(_______________________________));
                                                          ^
10      }
11  }
Program.cs(9,34): error CS0311: The type 'Program.Tag' cannot be used as type parameter 'T' in the generic type or method 'Program.Clamp<T>(T, T, T)'. There is no implicit reference conversion from 'Program.Tag' to 'System.IComparable<Program.Tag>'.

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

cannot be used as type parameter の原因と直し方

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)