【问题标题】:static using doesn't recognize method name, saying the name does not exist in the current context静态使用不识别方法名称,说出当前上下文中的名称不存在
【发布时间】:2020-06-06 03:01:49
【问题描述】:

请注意:我知道a similar question 已经有been answered。我花了一段时间才找到那个问题/答案,因为它假设我认识到它特别涉及扩展方法,而我一开始并没有。我错误地假设static using 功能只能与扩展方法一起使用,所以由于它被认为是多余的,我在搜索时没有包括它。

这篇文章的目的是帮助那些不了解这一点的人。


我有一些在 C# 6 中引入的using static directive 代码:

using static MyNs.MyExtensionMethods;

我正在尝试使用MyNs.MyExtensionMethods 中定义的扩展方法,并且它有效(一如既往):

foo.MyExtensionMethod();

但这不是:

MyExtensionMethod(foo);

我收到编译器错误“当前上下文中不存在名称 'MyExtensionMethod'”。怎么回事?

【问题讨论】:

    标签: c# .net static extension-methods using-directives


    【解决方案1】:

    正如this answer 所指出的,您不能使用using static 指令来允许对扩展方法 的非限定访问,只能访问常规静态方法(即第一个参数上没有this 关键字)。原因在那个答案里已经说得很清楚了,这里就不重复了。

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 1970-01-01
      • 2013-10-02
      • 2014-04-22
      • 2017-06-17
      • 2015-09-11
      • 1970-01-01
      • 2015-09-30
      相关资源
      最近更新 更多