Yon*_*ona 5 .net c# extension-methods .net-3.5
我创建了一个单独的程序集来包含常见的扩展方法,扩展方法使用来自System.Web.dll(和其他)的类.
然后,当我创建一个引用Utilities.dll包含扩展方法的程序集的新项目(控制台应用程序)时,System.Web.dll如果它不使用扩展程序中任何类的扩展方法,则不需要添加对新项目的引用System.Web.dll(例如System.Web.UI.Control).
当其中一个扩展方法是通用方法时,一切都会按预期继续工作.但是,只要我将约束添加到将其约束到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();
}
}
Run Code Online (Sandbox Code Playgroud)
And here is a new console application that won't compile (unless I also add a reference to System.Web.dll
System.Web.dll):
static void Main(string[] args)
{
bool isEmpty = "Hello World!".IsNullOrEmpty();
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
Utilities.dll was already used as a parameter to the method. and why is the namespace the solution when I already use the using 指令在顶部.
嗯,是!为了编译,它需要能够解析公共/受保护API中的所有内容.否则它无法强制执行约束.我想它需要识别类型以查看扩展方法是否是方法的候选者.
您可以尝试将扩展方法放在其中包含"Web"的子命名空间中 - 至少它不会溢出到常规代码中.我已经检查了,这解决了这个问题.最好将扩展方法的命名空间分开,以允许调用者控制它们何时应该在范围内.
为了执行,还需要能够在内部解决,但使用任何没有在API中暴露出来.这是标准行为.