C#: why can I not create a system namespace?
I remember few weeks ago when I reorgnized our code and created some namespaces in our project I got error and the system did not allow me to create a companyName.projectName.System
namespace, I had to change it to companyName.projectName.Systeminfo
. I don't know why. I know there is a System
namespace but it is not companyName.projectName.System
. I think A.B.C
namespace should be different with A.A.C
namespace. Right?
EDIT
The error I got is like the this:
Error 7 The type or namespace name 'Windows' does not exist in the namespace 'MyCompany.S开发者_高级运维ystemSoftware.System' (are you missing an assembly reference?) C:\workspace\SystemSoftware\SystemSoftware\obj\Release\src\startup\App.g.cs 39 39 SystemSoftware
You're experiencing a namespace clash.
If you name the last part of your namespace System, then the compiler will have a hard time determining if you're referring to the (Microsoft) System namespace or an inner System namespace at your current level (or even an System class or property or ...).
You'll experience the same problem with class names and namespace parts. You can't create a class called System for the same reasons.
Unless you feel like specifying full namespaces for all of your instances.
The code below compiles and runs, so I think you'll need to give us a bit more detail as there's no reason you can't create a namespace such as companyName.projectName.System
as far as I'm aware.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var x = new ConsoleApplication1.Project.System.Something();
}
}
}
namespace ConsoleApplication1.Project.System
{
public class Something
{
}
}
It's probably because you can use relative namespaces in .NET.
if you have an object in the namespace A.B.C, then when you are coding in the namespace A.B, you can refer to that object as just C.ObjectName, instead of A.B.C.ObjectName. Therefore, if you were at the companyName.projectName level, System would be abiguous, unelss you were to start using namespace aliases.
However, I found the best approach is to avoid the thing that is causing the confusion in the first place, and change your System namespace to something else, and it all ceases to be a continuing problem.
C# can only get confused. Please read the following topic on Eric Lippert's blog. I know that he speaks about classes and namespaces, but the same or other related behaviour may occur.
Eric Lippert just posted on a closely related issue. http://blogs.msdn.com/ericlippert/archive/2010/03/09/do-not-name-a-class-the-same-as-its-namespace-part-one.aspx
By creating x.y.System for code in the x.y namespaces it becomes difficult to determine if you are referring to x.y.System.Foo or System.Foo.
I would come up with a different name for the sake of clarity.
精彩评论