共通の拡張メソッドを含む別のアセンブリを作成しました。拡張メソッドはSystem.Web.dll
(およびその他) のクラスを使用します。
次に、拡張メソッドを含むアセンブリを参照する新しいプロジェクト (コンソール アプリケーション) を作成するときに、アセンブリ内のクラスを拡張する拡張メソッドを使用しない場合は、新しいプロジェクトへUtilities.dll
の参照を追加する必要はありません(たとえば)。System.Web.dll
System.Web.dll
System.Web.UI.Control
拡張メソッドの 1 つがジェネリック メソッドになる場合、すべてが期待どおりに機能し続けます。しかし、アセンブリ内のクラスに制約するジェネリック メソッドに制約を追加するとすぐにSystem.Web.dll
、コンパイラはSystem.Web.dll
、新しいプロジェクトがまだそのアセンブリ内で何も使用していない場合でも、新しいプロジェクト (コンソール アプリケーション) への参照が必要であると不平を言います。 .
言い換えれば、ジェネリックメソッドに制約がない限り、すべてがコンパイルされますが、制約を追加するとすぐにコンパイラが文句を言います。
私の拡張メソッド アセンブルの例 (ライブラリとしてコンパイル)Utilities.dll
):
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
}
public static class ControlExtensions
{
// If I remove the where clause it compiles
public static T FildChild<T>(this Control parent, string id)
where T : Control
{
throw new NotImplementedException();
}
}
And here is a new console application that won't compile (unless I also add a reference to System.Web.dll
):
static void Main(string[] args)
{
bool isEmpty = "Hello World!".IsNullOrEmpty();
Console.ReadLine();
}
Update:
As Marc pointed out (below) puting the offending method in a separate namespace fixes the problem.
上のディレクティブ。But the question still remains why is the constraint a problem while the type Control
was already used as a parameter to the method. and why is the namespace the solution when I already use the using