简体   繁体   中英

Weird C# namespace issue

I've got a project with several namespaces and many classes contained within one of them ->

Some.Namepsace. (namespace)
               ExistingClass (class)
               ExistingClass2 (class)
               Constants (class)
                        .Enum (enum)

Within this project I created a class, but with an incorrect namespace like so

namespace Some.Namespace.Some.Namespace
{
    public class NewClass {}
}

Now Some.Namespace.ExistingClass cannot resolve a reference to Some.Namespace.Constants.Enum - it appears to be looking for Some.Namespace.Some.Namespace.Constants.Enum.

Any idea why? NewClass does not reference anything, and is not referenced by anything so I don't see how it's namespace could affect any other components. I fixed the namespace issue on NewClass , and that fixes it.

A class inside Some.Namespace.Some.Namespace will try to resolve Some.Namespace.Constants.Enum as: Some.Namespace.Some.Namespace.Constants.Enum , not Some.Namespace.Constants.Enum .

It would work if you tried to refer to the Enum as: global::Some.Namespace.Constants.Enum .

This must have something to do with the way C# in visual studio/csc attempts to resolve references. It would appear it goes something like this:

  • Look relative to the namespace of the calling object
  • If such a namespace is not found, attempt to look up the reference as if it's absolute

In my case, before I added Some.Namespace.Some.Namespace.NewClass , when VS tried to resolve the reference from Some.Namespace.ExistingClass to Some.Namespace.Constants.Enum , it first attempted a relative namespace lookup (starting from ExistingClasse's Some.Namespace ), found no such namespace. It then attempted an absolute lookup and found it.

After I added Some.Namespace.Some.Namespace.NewClass , it found the namespace, noticed the object was not there, and decided to discontinue searching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM