在 C# 中的多个类中使用相同的命名空间是一种常见的做法吗 [英] Is it common practice to use the same Namespace in multiple classes in C#

查看:90
本文介绍了在 C# 中的多个类中使用相同的命名空间是一种常见的做法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道命名空间的用途,但我不确定使用命名空间时程序的结构应该如何.

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

1- 您是否对程序中的所有相关类使用相同的 namespace 名称,还是为每个类使用不同的命名空间?

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- 如果唯一命名空间更常见,使用与类相同的名称是否常见?

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

有人能给我一些关于如何在 C# 中使用 namespace 的一般建议吗?

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

使用相同命名空间名称的示例:

// 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...");
        }
    }
}

推荐答案

来自 MSDN 是有一些解释.对于 c# 中使用的命名空间和示例.

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

更新:对于你的第一个问题,我试着用一些简单的例子来解释.例如,让我们有图书馆.这就像 head 命名空间.在这个图书馆里你有书.每本书都是一些对象.这本书在命名空间库中.所以可能只有一个命名空间Library.BookName".您可以将 head 命名空间中的每个类都设置为图书馆",但通常情况下,图书馆书籍的部分是分开的,例如(科幻、体育等).最好有Library.Sport.BookName"之类的命名空间.

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.

这篇关于在 C# 中的多个类中使用相同的命名空间是一种常见的做法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆