Is it common practice to use the same Namespace in multiple classes in C#

丶灬走出姿态 提交于 2021-01-28 20:12:44

问题


I know what namespace is for but I'm not sure how the structure of a programs should be when using namespaces.

1- Do you use the same namespace name for all related classes in a program or do you use different namespace for each class?

2- If a unique namespace is more common, is it common to use the same name as the class?

Can some one give me some general advice on how namespace is used in C#?

Example using the same namespace name:

// Main program
using System;
using Zoo;

public class Program {
    public static void Main()
    {
        Dog buddy =  new Dog();
        buddy.bark();
        buddy.run();
    }
}

// Animal class
namespace Zoo{
    class Animal{
        public void run(){
            Console.WriteLine("Running...");
        }
    }
}

// Dog Class
namespace Zoo{
    class Dog:Animal{
        public void bark(){
            Console.WriteLine("Barking...");
        }
    }
}

回答1:


Here is Microsoft's own guidelines regarding namespaces:

Guidelines

I hope this helps.




回答2:


From MSDN Is have some explaned. For what is used namespace in c#, and examples.

UPDATE: For your first question, I try to explain with some simple example. For example let's we have Library. This is like head namespace. In this Library you have books. And every book is some object. And this book is in namespace Library. So is possible to have only one namespace 'Library.BookName'. You can make every class in head namespace 'Library', But in common case in library books is separate in sections, like (sci-fi, sports etc.). And is better to have 'Library.Sport.BookName' like namespace.

And back in your question. You can use the same namespace for every class. But is better to separate in few namespaces, not to be in one namespace.



来源:https://stackoverflow.com/questions/35772995/is-it-common-practice-to-use-the-same-namespace-in-multiple-classes-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!