C# 扩展方法似乎不存在
我似乎无法在同一命名空间(MyProject.Util
)的另一个类中找到以下扩展方法。
using System.Collections.Specialized;
namespace MyProject.Util
{
public static class Extensions
{
public static string Get(
this NameValueCollection me,
string key,
string def
)
{
return me[key] ?? def;
}
}
}
正如你所看到的,它基本上是 foo[bar] 的另一个版本? baz,但我仍然不明白为什么 VS2008 无法编译并告诉我没有任何版本的 Get
接受两个参数。
有什么想法吗?
I can't seem to get the following extension method to be found in another class in the same namespace (MyProject.Util
).
using System.Collections.Specialized;
namespace MyProject.Util
{
public static class Extensions
{
public static string Get(
this NameValueCollection me,
string key,
string def
)
{
return me[key] ?? def;
}
}
}
As you can see it's basically another version of foo[bar] ?? baz
, but I still don't understand why VS2008 fails to compile telling me that no version of Get
takes two arguments.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您是否正在使用该方法的文件中导入您的命名空间(使用
using MyProject.Util
)?该错误消息可能并不明显,因为您的扩展方法与现有方法具有相同的名称。Are you importing your namespace (with
using MyProject.Util
) in the file where you're using the method? The error message might not be obvious because your extension method has the same name as an existing method.您不能像
NameValueCollection.Get
中的静态方法一样使用扩展方法。尝试:You can't use the extension method like a static method as in
NameValueCollection.Get
. Try:该类是否与使用它的类位于同一个程序集中?如果没有,您是否添加了对该程序集的引用?
Is the class in the same assembly as the class where it is being used? If no, have you added a reference to that assembly?
以下似乎对我有用......
您检查过您的目标框架吗?
The following seems to work for me ...
Have you checked your target framework?
当我尝试时效果很好。实际上只有一种失败模式:忘记为包含扩展方法的命名空间添加 using 语句:
Works fine when I try it. There's really only one failure mode: forgetting to add a using statement for the namespace that contains the extension method:
我最近遇到了类似的问题,并追溯到没有引用 System.Core(该项目是针对 3.5 编译的,但在尝试 VS2010/.Net 4.0 时该引用被意外删除)。
I had a similar issue recently and traced it down to not referencing System.Core (the project was compiled against 3.5, but that reference had accidentally been removed while experimenting with VS2010/.Net 4.0).