C# 命名空间、类、对象和实例之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/819793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:27:38  来源:igfitidea点击:

What is the difference between a namespace, a class, an object and an instance?

c#oopnamespaces

提问by RocketGoal

I'm reading Heads First C# (it's very interesting and user-friendly), but I wondered if anyone had a useful metaphor for describing how Name spaces, Classes, methods, properties, etc. all 'fit together'?

我正在阅读 Heads First C#(它非常有趣且用户友好),但我想知道是否有人有一个有用的比喻来描述名称空间、类、方法、属性等如何“组合在一起”?

Is Class a Parent and a Method a child, etc. Or is it more complicated?

类是父类,方法是子类等等。还是更复杂?

Could a Name Space be a house, and a Class be a room (Bathroom) and a method be what can be done in that room (wash, etc.) and the properties be what can be done when doing that activity, use soap, hot water...

命名空间可以是房子吗,类可以是房间(浴室),方法可以是在那个房间里可以做什么(洗涤等),而属性可以是在做那个活动时可以做什么,使用肥皂,热水...

...I'll get my coat.

……我去拿外套。

采纳答案by sharkin

I would say:

我会说:

  • Namespace: A category or brand of cars. Note that the brand really doesn't have to dictate how the car is built. You can't say a Honda always have four doors, or that it always has 4wd. Such specifics is up to the class to dictate. Rich.Carpenter's postexplains the purpose of namespaces very well.

  • Class: Blueprint for how to build a specific car.

  • Object: An actual car (instance) created from the car blueprint (the class)

  • Method: Something a user of the car can make it do. Start(), IncreaseThrottle(), Brake(), OpenDoor(), etc.

  • Property: Attributes, information and building blocks which the car contains. E.g. Total running miles, color, steering wheel dimension, stereo system etc etc.

  • 命名空间:汽车的类别或品牌。请注意,品牌实际上不必决定汽车的制造方式。你不能说本田总是有四扇门,或者它总是有 4wd。此类细节由班级决定。Rich.Carpenter 的帖子很好地解释了命名空间的用途。

  • :如何建造特定汽车的蓝图。

  • 对象:从汽车蓝图(类)创建的实际汽车(实例)

  • 方法:汽车用户可以做的事情。Start()IncreaseThrottle()Brake()OpenDoor(),等。

  • 属性:汽车包含的属性、信息和构建块。例如总行驶里程、颜色、方向盘尺寸、立体声系统等。

Some concepts which could seem more advanced to you. Maybe overkill right now, but read it if you're interested:

一些对您来说似乎更高级的概念。现在可能有点矫枉过正,但如果您有兴趣,请阅读:

  • Inheritance: When a class is based on another class and adds some more specific details. A line of inheritance usually goes from the most common and general aspect, all the way down to a point where it makes no more sense to be more specific. Example of this in the context of animals: Animal->Mamal->Rodent->Rat->RattusNorvegicus

  • Aggregates: Properties that "builds" the object. E.g. "This car is an aggregation of four wheels, a chassis, an engine, etc".

  • Attribute: Properties that describe the object, usually not part of its physical construction. E.g. Color, top speed, engine volume etc.

  • Encapsulation: The concept of concealing certain properties from the user, or to protect certain properties from being used incorrectly (and thereby damaging the object). E.g. You don't expose the gear-property of a car class to be altered freely. You encapsulate it and make sure Clutch()is called before SetGear().

  • Overriding: If a class inherits from another class, it also inherits methods from that class. Overriding is basically when the inheritingclass replaces the implementation of such a method with its own required behaviour. Example of usage in next point.

  • Polymorphism: A difficult concept to grasp until you start using it practically. It means referring to a very specific kind of object, by using a generic reference which allows you to ignore the specific type (when you don't need to know it). E.g. If you want to "read" the license plate number property of every vehicle in a parking lot, you don't really care what the brand is, or even if it's a trailer or motorcycle or whatever. To be able to do this, we make sure the license plate number is a property in the most general class in the inheritance line (probably the Vehicleclass). So you only have to deal with all the objects in a list by referring to them as their Vehicleclass and then calling Vehicle::GetLicensePlateNumber(). Any vehicle requiring some special handling to retrieve the number can implement this behaviour by overriding the method and make it behave as required. So, a wide range of object types can be used as if they were of the same type, but can behave differently.

  • 继承:当一个类基于另一个类并添加一些更具体的细节时。继承线通常从最常见和一般的方面开始,一直到某个点,再具体一点就没有意义了。在动物上下文中的示例:Animal->Mamal->Rodent->Rat->RattusNorvegicus

  • 聚合:“构建”对象的属性。例如“这辆车是四个轮子、一个底盘、一个发动机等的集合体”。

  • 属性:描述对象的属性,通常不是其物理构造的一部分。例如颜色、最高速度、发动机音量等。

  • 封装:向用户隐藏某些属性,或保护某些属性不被错误使用(从而损坏对象)的概念。例如,您不会公开要自由更改的汽车类的齿轮属性。您封装它并确保Clutch()在 之前被调用SetGear()

  • 覆盖:如果一个类从另一个类继承,它也从该类继承方法。覆盖基本上是当继承类用它自己所需的行为替换这种方法的实现时。下一点的用法示例。

  • 多态:一个很难掌握的概念,直到你开始实际使用它。这意味着通过使用允许您忽略特定类型的泛型引用(当您不需要知道它时)来引用一种非常特定的对象。例如,如果您想“读取”停车场中每辆车的车牌号属性,您并不真正关心品牌是什么,甚至是拖车、摩托车或其他任何东西。为了能够做到这一点,我们确保车牌号是继承行中最通用的类​​(可能是Vehicle类)中的一个属性。所以你只需要处理列表中的所有对象,将它们称为它们的Vehicle类,然后调用Vehicle::GetLicensePlateNumber(). 任何需要一些特殊处理来检索号码的车辆都可以通过覆盖该方法来实现此行为并使其按要求运行。因此,可以像使用相同类型一样使用多种对象类型,但它们的行为可能不同。

回答by Rich.Carpenter

Think of classes as descriptions of objects and methods as actions those object can perform.

将类视为对象的描述,将方法视为这些对象可以执行的操作。

For example, I design a new car. The plans or blueprints (classes) for that car are what is used to create actual, physicial cars (objects). Those plans indicate that the car should have a functional horn. Therefore, I have designed honking functionality (a method) into the car. Those plans also indicate that the car have four wheels. Wheels would be a property of the car with an instantiated (assigned to the property when the object is created) value of 4. Color would be another possible property. Properties describe object qualities or characteristics (color, height, width, etc.).

例如,我设计了一辆新车。那辆车的计划或蓝图(类)用于创建实际的物理汽车(对象)。这些计划表明汽车应该有一个功能性的喇叭。因此,我在汽车中设计了鸣喇叭功能(一种方法)。这些计划还表明该车有四个轮子。Wheels 将是汽车的一个属性,其实例化(在创建对象时分配给该属性)值为 4。颜色将是另一个可能的属性。属性描述对象的质量或特征(颜色、高度、宽度等)。

Now, I work for Toyota (not really, but bear with me). Toyota would be the namespace that includes my car blueprint. Since Ford, GM, etc. can all have their very own car designs (classes) as well with the very same names (car) and methods (honk), the namespaces of Toyota, Ford and GM keep those blueprints (classes) separate and distinct, as you can have multiple versions of classes and methods with the same name in an application when they have different namespaces.

现在,我为丰田工作(不是真的,但请耐心等待)。Toyota 将是包含我的汽车蓝图的命名空间。由于福特、通用汽车等都可以拥有自己的汽车设计(类)以及相同的名称(汽车)和方法(喇叭),因此丰田、福特和通用汽车的命名空间将这些蓝图(类)分开并不同,因为当应用程序具有不同的命名空间时,您可以在应用程序中拥有多个版本的具有相同名称的类和方法。

Hope that helps.

希望有帮助。

回答by Guffa

Classes are generally used to represent some kind of object. It could resemble a physical object like an invoice, but it could also be something more abstract.

类通常用于表示某种对象。它可以类似于发票等实物,但也可以是更抽象的东西。

Animals are sometimes used as examples for classes, because we are familiar with how animals work. So, let's use some animals:

动物有时被用作类的例子,因为我们熟悉动物的工作原理。所以,让我们使用一些动物:

Classes could be a kind of animal, like Catand Dog. When you create an instance of a class it becomes a specific object, like Fido the dog.

类可以是一种动物,例如CatDog。当你创建一个类的实例时,它会变成一个特定的对象,就像 Fido the dog。

Namespaces are used to group classes logically, so the Catand Dogclasses could be placed in the namespace Animals.Pets. Although namespaces are hierarchical, that doesn't make the classes in them hierarchical. They are just different groups, so the classes in the Animalsnamespace are not automatically parents to the classes in the Animals.Petsnamespace.

命名空间用于在逻辑上对类进行分组,因此CatDog类可以放在命名空间中Animals.Pets。尽管命名空间是分层的,但这并不会使它们中的类分层。它们只是不同的组,因此Animals命名空间中的类不会自动成为命名空间中类的父级Animals.Pets

Methods is something that the objects do, like Eat()and Sleep().

方法是对象所做的事情,例如Eat()Sleep()

Properties is something that describes an aspect of an object, like NumberOfLegsand IsSleeping.

属性是描述对象的一个​​方面的东西,例如NumberOfLegsIsSleeping

回答by MoSlo

I would say your classes might be job positions, performing different actions (the actions being methods, in other words). You may have various individual people performing the actions (the various instances of the objects).

我会说您的课程可能是工作职位,执行不同的操作(换句话说,操作是方法)。您可能有不同的个人执行操作(对象的各种实例)。

These collections of job positions would reside in a department. Finance has its jobs/classes (accountants, book-keepers..) but they would need to work with Sales, who have their own types of jobs/classes.

这些工作职位的集合将驻留在一个部门中。财务有自己的工作/课程(会计师、簿记员......),但他们需要与销售合作,他们有自己的工作/课程类型。

In this sense, the various departments are the namespaces. people working in Sales need to eventually work with Finance. Multiple departments (or namespaces) are working together to achieve a goal.

从这个意义上说,各个部门就是命名空间。在销售部门工作的人最终需要与财务部门合作。多个部门(或命名空间)正在协同工作以实现一个目标。

Now these departments may be part of a company; that company would be the root namespace of all these departments. And in such a manner, namespaces can exist and be nested together.

现在这些部门可能是公司的一部分;该公司将成为所有这些部门的根命名空间。以这种方式,命名空间可以存在并嵌套在一起。

In a nutshell, namespaces pretty much segregate responsibilities.

简而言之,命名空间几乎隔离了职责。

Imagine multiple companies working together (Microsoft .net namespaces working with your own namespace) and you get the greater picture.

想象一下多个公司一起工作(Microsoft .net 命名空间与您自己的命名空间一起工作),您将获得更大的图景。

回答by z -

in one sentence:

一句话:

an Objectis an Instanceof a Class

一个对象是一个实例一的

回答by Eppz

An object can be an instance of a class?

对象可以是类的实例吗?

回答by PaulJWilliams

A class defines what an object looks like - what data it contains, what methods it has, and what other classes its related to.

一个类定义了一个对象的样子——它包含什么数据,它有什么方法,以及它与哪些其他类相关。

An instance is a single created entity of that class - its an object created by using the class definition as a reference.

实例是该类的单个创建实体 - 它是通过使用类定义作为引用创建的对象。

回答by thomasrutter

A class is a type of object. For example, you can have as many objects of one class as you want.

类是一种对象。例如,您可以根据需要拥有任意数量的一类对象。

An instance is an object, and sometimes the two terms are used interchangeably, because in many languages, all objects are also instances of a class. People use the word 'instance' to make it explicit that they are not talking about a class, but an object of that class.

实例是一个对象,有时这两个术语可以互换使用,因为在许多语言中,所有对象也是一个类的实例。人们使用“实例”这个词来明确表示他们不是在谈论一个类,而是该类的一个对象。

回答by Bill the Lizard

A classis a template for an object. It's the source code that tells the compiler what member variables and methods go into an object of that type of class.

是对象的模板。源代码告诉编译器将哪些成员变量和方法放入该类型的类的对象中。

An objectand an instanceare really the same. From the class template you can create many instances (or objects) of the class. Each one has all the members and methods defined in the class, in its own memory (although you can have shared members, and methods are almost always shared between instances).

一个对象和一个实例实际上是一样的。从类模板中,您可以创建该类的许多实例(或对象)。每一个都有在类中定义的所有成员和方法,在它自己的内存中(尽管你可以有共享成员,方法几乎总是在实例之间共享)。

回答by Lasse V. Karlsen

By using an analogy for house blueprints.

通过使用房屋蓝图的类比。

The blueprint is a class. It specifies lots of details, but also leaves out a lot of properties, like the color of the house, the color and style of the front door, etc. You know, by checking the blueprint, where the door is going to be though, and that there isa door.

蓝图是一个类。它指定了很多细节,但也遗漏了很多属性,比如房子的颜色,前门的颜色和风格等。 你知道,通过检查蓝图,门的位置,并有一扇门。

An object is the house you build from that blueprint. You can have many houses built from the same blueprint. They all have the same overall look and layout, but properties might vary, like the color of outside paint, the style of the front door, etc. The front door is in the same place on all the houses though.

对象是您根据该蓝图建造的房屋。您可以根据同一个蓝图建造许多房屋。它们的整体外观和布局都相同,但属性可能会有所不同,例如外墙涂料的颜色、前门的风格等。尽管所有房屋的前门都在同一个位置。

You can call each of these houses instances of the house from the specific blueprint.

您可以从特定蓝图中调用这些房屋中的每一个实例。

So, as @yxso eloquently said, an object is an instance of a class.

所以,正如@yx所说的那样,一个对象是一个类的实例。