名称空间与类声明 [英] Namespace vs Class Declaration

查看:153
本文介绍了名称空间与类声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我似乎找不到任何信息,所以我会在这里问。

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

命名空间中的类必须

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());
    }
}

我能正确理解吗?

推荐答案

命名空间只是一个清楚说明类在哪个上下文中的方式。想想你自己的名字,Ralph。我们在这个世界上有许多Ralph,但其中之一就是你。一个额外的方法来消除歧义是添加你的姓。所以如果我们有2个Ralph,我们有更大的机会谈论你。

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.

类同样的作品。如果你定义类 AClass ,你需要定义另一个类 AClass ,就没有办法区分他们俩。命名空间将是'surname'。

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.

例如:

using System;

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

由于使用系统; 您不必声明 Console 的命名空间。只有一个控制台可用,它位于 System 命名空间中。如果你不会使用System; 命名空间声明你的,那么你需要解释在哪里可以找到 Console 。像这样。

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");

从MSDN:



namespace关键字用于声明作用域。此命名空间范围允许您组织代码,并为您提供了一种创建全局唯一类型的方法。

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.


有关详情,请查看命名空间的MSDN

这篇关于名称空间与类声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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