1

我创建了以下类:

using System.Windows;
using System.Windows.Input;
using MyUtils.MyArgParser;

namespace MyUtils.MyImplement
{
    public static class ImplementExitOnEscape
    {
        #region ImplementExitOnEscape

        public static void Implement(Window window)
        {
            window.KeyDown += Window_KeyDown;
        }

        private static void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var window = sender as Window;
            // Close window when pressing the escape key.
            if (e.Key == Key.Escape) if (window != null) window.Close();

            var optionX = MyArgParser.MyArgParser.GetOptionValue("optionX");
        }

        #endregion //ImplementExitOnEscape
    }
}

为什么我被迫使用MyArgParser类的全名空间var optionX = MyArgParser.MyArgParser.GetOptionValue("optionX");而不是 just MyArgParser.GetOptionValue("optionX");

using MyUtils.MyArgParser;被忽略。有没有它不会有任何区别,编译器仍然强迫我使用完整的命名空间。

我觉得这很奇怪,因为它并非无处不在。例如,我不需要在定义了我的应用程序入口点的文件中使用完整的命名空间。

4

4 回答 4

7
var optionX = MyArgParser.MyArgParser.GetOptionValue("optionX"); 

您的类被命名为您的命名空间,因此要区分它们,您需要显式地完全引用它。

要解决它,请将您的 MyArgParser 命名空间更改为(例如)MyArgParserNS,您可以直接使用它

using MyUtils.MyArgParserNS

进而:

var optionX = MyArgParser.GetOptionValue("optionX"); 

或者,好吧,完全参考它。

于 2012-09-22T14:46:13.993 回答
6

问题是您有一个与其命名空间同名的类,这意味着编译器无法区分 MyArgParser.GetOptionValue 中的 MyArgParser 是命名空间还是类。

由于每个文件顶部的不同 using 语句或名称与类名冲突的字段或变量,它可能会也可能不会强制您使用完整的命名空间。有关该主题的更多信息,请参阅Eric Lippert 的博客文章(以及第 2、34部分)。

请参阅如何避免类及其名称空间具有相同的名称,例如 Technology.Technology?对此进行更多讨论。

于 2012-09-22T14:46:13.080 回答
1

您在声明之外有您的using指令。编译器按以下顺序在这些位置namespace搜索类型或命名空间:

  1. MyUtils.MyImplement.ImplementExitOnEscape(当前类型内的嵌套类型)
  2. MyUtils.MyImplement(当前命名空间中的类型或命名空间)
  3. MyUtils(“下一个”外层的类型或命名空间)
  4. 空命名空间或全局命名空间(类型或命名空间)
  5. System.Windows, System.Windows.Input, 并且MyUtils.MyArgParser你有usings for (类型或命名空间)

您输入MyArgParser.了 <something>。

(3.)中找到了一个匹配项,那就是namespace。只有在 (5.) 中你的using问题。所以MyArgParser指的是命名空间,而不是类型。

如果您将usings 放入namespace块中,情况会有所不同,请在另一个线程中查看我的答案

于 2013-05-18T19:33:32.410 回答
0

可能有几个原因:

  1. 与其他名称冲突

  2. 你的班级可能是另一个名字。

使用 Ctrl+J+K,然后搜索您的班级。看看 VS 有没有找到。如果不是,那么可能是因为参考问题。您需要添加对该库的引用吗?

于 2012-09-22T14:46:59.590 回答