我的命名空间有什么问题?

5Yr*_*DBA 2 c# namespaces

我正在重命名项目中的命名空间.我发现了一件奇怪的事情,无法理解为什么会这样?

原始结构:

namespace Mycompany.Util
{
    public class Util{
        public static void ReadDictionaryFile()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在另一个文件中

using MyCompany.Util;

namespace Logging {
    public class Log {
        public void MethodB() {
            ...
            Util.ReadDictionaryFile();
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面工作正常,没有编译错误.

然后我将Logging命名空间更改为MyCompany.Logging,我在MethodB中立即收到错误告诉我

"Error 5 The type or namespace name 'ReadDictionaryFile' does not exist in the namespace 'MyCompany.Util' (are you missing an assembly reference?) C:\workspace\SystemSoftware\SystemSoftware\src\log\Log.cs 283 61 SystemSoftware
"
Run Code Online (Sandbox Code Playgroud)

我必须改变那个函数调用Util.ReadDictionaryFile(),MyCompany.Util.Util.ReadDictionaryFile()我不知道为什么?系统库中是否有另一个Util类?

整个使用线遵循:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MyCompany.Util;
Run Code Online (Sandbox Code Playgroud)

编辑:

在C#中,当我们调用静态方法时,我们必须这样调用:namespace.classname.methodname?好的,我只是来自Java.在Java中,使用后可以使用import MyCompany.Util.*;以下格式调用静态方法:className.methodName;,不需要包名.

EDIT2:

className.methodName;如果我们正确使用命名空间,C#和Java是相同的,足以调用静态方法.

Jon*_*gel 11

MyCompany.Util.Util.ReadDictionaryFile()

这是namespace.namespace.class.method,在您的第一个代码块中定义.

是的,如上所述,拼写错误可能无济于事.

编辑:此代码示例编译正常.

namespace MyCompany.Util
{
    public class Util
    {
        public static void ReadDictionaryFile()
        {
        }
    }
}

namespace MyCompany.Logging
{
    using MyCompany.Util;

    public class Log
    {
        public void MethodB()
        {
            Util.ReadDictionaryFile();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我取出using指令,那么我必须完全限定命名空间,除非默认命名空间是MyCompany,在这种情况下你只需要限定Util 命名空间,Util.Util.ReadDictionaryFile().


Jac*_*b G 10

问题是,当您添加父命名空间MyCompanyLogging,编译器会解析UtilUtil命名空间中的MyCompany命名空间而不是命名空间中的UtilMyCompany.Util.

  • 好点!+1专业提示:永远不要将名称与命名空间相同. (2认同)