Namespace vs Class Declaration

2019-04-14 16:07发布

问题:

I'm new to C# and I can't seem to find any info on this so I will ask it here.

Do classes in namespaces have to ever be declared?

using System;
public class myprogram
{
    void main()
    {
        // The console class does not have to be declared?
        Console.WriteLine("Hello World");
    }
}

If I'm not using a namespace then I have to declare a class

class mathstuff
{
    private int numberone = 2;
    private int numbertwo = 3;
    public int addhere()
    {
        return numberone + numbertwo;
    }


using System;
public class myprogram
{
    void main()
    {
        // the class here needs to be declared.
        mathstuff mymath = new mathstuff();
        Console.WriteLine(mymath.addhere());
    }
}

Am I understanding this correctly?

回答1:

A namespace is simply a way to make clear in which context the class is living in. Think of your own name, Ralph. We have many Ralphs in this world, but one of that is you. An extra way to get rid of the ambiguity is to add your surname. So that if we have 2 Ralphs, we have a bigger chance of talking about you.

The same works for classes. If you define class AClass and you would have the need of define another class AClass there would be no way to distinguish between the two. A namespace would be that 'surname'. A way of having to classes, but still able to distinguish between the two different classes, with the same name.

To answer your question, it has nothing to do with "not having to declare". It would only be easier to write code.

For example:

using System;

public class myprogram
{
    void main()
    {
        // the class here needs to be declared.
        Console.WriteLine("blah");
    }
}

Because of the using System; you don't have to declare the namespace of Console. There is only one Console available, which lives in the System namespace. If you wouldn't declare your using System; namespace then you'd need to explain where Console can be found. Like this.

System.Console.WriteLine("blah");

From MSDN:

The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.

For more info check MSDN for namespace.



回答2:

I think what you mean is "can you declare a class without a namespace?". Yes you can, it's referred to as the global namespace.

class BaseClass
{
}

class SubClass : global::BaseClass
{
}

However, this is very bad practice, and you should never do this in a production application.