C# 方法和构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1130199/
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
methods and constructors
提问by tintincutes
I'm learning C# now and a beginner in the programming world. I have a book called The Complete Reference by Herbert Schildt. So far its a good book and I'm in the middle of learning about methods and constructors.
我现在正在学习 C# 并且是编程世界的初学者。我有一本赫伯特·希尔特 (Herbert Schildt) 所著的《完全参考书》(The Complete Reference)。到目前为止,这是一本好书,我正在学习方法和构造函数。
I'm quite confused what's the difference of methods and constructors. Because in the book it has almost the same example. I don't know how to differentiate them. I would appreciate your idea. By the way I have several definition here of both, I just would like to know how to differentiate them
我很困惑方法和构造函数的区别是什么。因为在书中它有几乎相同的例子。我不知道如何区分它们。我会很感激你的想法。顺便说一下,我在这里对两者都有几个定义,我只是想知道如何区分它们
Thanks for your help
谢谢你的帮助
Cheers
干杯
采纳答案by Serhat Ozgel
A constructor only works when you create a new instance of a class. This is the very first method to run on an instance, it has to run, and it runs exactly once.
构造函数仅在您创建类的新实例时起作用。这是在实例上运行的第一个方法,它必须运行,并且只运行一次。
A method on an instance can be called anywhere between zero times to infinite times on an instance once it is created.
实例上的方法可以在实例创建后在零次到无限次之间的任何地方调用。
A constructor is run implicitly. When a new instance of a class is created, it runs automatically. A method is run explicitly. It has to be called either from some outside source or from a method -or a constructor- in the class.
构造函数是隐式运行的。创建类的新实例时,它会自动运行。一个方法是显式运行的。它必须从某个外部源或从类中的方法或构造函数调用。
A constructor is intended to be used for wiring. In the constructor, you want to avoid doing actual work. You basically prepare the class to be used. A method is intended to do actual work.
构造函数旨在用于接线。在构造函数中,您希望避免进行实际工作。您基本上准备了要使用的类。一种方法旨在完成实际工作。
public class MyType
{
private SomeType _myNeeds;
// constructor
MyType(SomeType iWillNeedThis)
{
_myNeeds = iWillNeedThis;
}
// method
public void MyMethod()
{
DoSomethingAbout(_myNeeds);
}
}
回答by Chris
A constructor is a method.. a special method that is being called upon "construction" of the class.
构造函数是一种方法……一种特殊的方法,它在类的“构造”时被调用。
Definition: A constructor is a class member function in C++ and C# that has the same name as the class itself.
The purpose of the constructor is to initialize all member variables when an object of this class is created. Any resources acquired such as memory or open files are typically released in the class destructor.
定义:构造函数是 C++ 和 C# 中与类本身同名的类成员函数。
构造函数的目的是在创建该类的对象时初始化所有成员变量。获取的任何资源(例如内存或打开的文件)通常在类析构函数中释放。
From About.com
回答by sharptooth
A constructor is an instance method with special meaning - specifically it is called internally when creating an instance of the corresponding class with new. That's the key difference.
构造函数是一个具有特殊含义的实例方法 - 特别是在使用new创建相应类的实例时在内部调用它。这是关键的区别。
Other minor differences are that the constructor must have the same name as the class it belongs to and it can't have any return value, even void.
其他细微的区别是构造函数必须与它所属的类同名,并且不能有任何返回值,甚至是 void。
回答by Kevin Peterson
In terms of how they operate on the object, they behave similarly. A constructor is a method of the object, but it's a special method.
就它们如何操作对象而言,它们的行为相似。构造函数是对象的一个方法,但它是一个特殊的方法。
What makes it special is how it gets called from outside. A constructor is called as part of the process of creating the object. Normal methods get called explicitly on the object (after it is done being created).
它的特别之处在于它是如何从外部调用的。在创建对象的过程中调用构造函数。在对象上显式调用普通方法(在创建完成后)。
回答by Ionu? G. Stan
The constructor method name has the same name as the class. Also, it does not have a return type. Or, if you will, the constructor method itself has no name, but the return type is the class type.
构造方法名称与类同名。此外,它没有返回类型。或者,如果您愿意,构造函数方法本身没有名称,但返回类型是类类型。
public class Foo
{
// Constructor
public Foo()
{ }
public void Bar()
{ }
}
回答by Michiel Buddingh
In terms of what they're allowed to do, constructors don't differ all that much from methods. The main conceptual difference between a method and a constructor is its purpose.
在方面他们被允许做什么,构造差异并不太大全部从方法这一点。方法和构造函数之间的主要概念区别在于其目的。
A constructor brings an object into a valid, usable state, and is called only once, at the beginning. A method changesan object from one valid state to another. (Okay, some methods only retrieve information, they're not required to change the state of an object).
构造函数将对象带入有效、可用的状态,并且在开始时只调用一次。方法将对象从一种有效状态更改为另一种有效状态。(好吧,有些方法只检索信息,它们不需要更改对象的状态)。
Edit:It occurs to me that, particularly for C#, the above explanation might be confusing, as immutable objects aren't exactly uncommon idioms in the language, so a lot of objects the OP will encounter won't have a changeable state. Complex concepts often have one-line explanations that are simple, elegant and wrong.
编辑:我突然想到,特别是对于 C#,上面的解释可能会令人困惑,因为不可变对象在语言中并不是不常见的习惯用法,因此 OP 遇到的很多对象都不会具有可变状态。复杂的概念通常有简单、优雅和错误的单行解释。
回答by peterchen
class invariants
A class is responsible to preserve invariants - that is: a class makes guarantees to the caller, such as "object.weight
is never negative", "there are no duplicates in the list of names", etc.
类不变量
类负责保留不变量——即:类向调用者做出保证,例如“object.weight
永远不会为负”、“名称列表中没有重复项”等。
A method manipulates an existing object, thus can rely on class invariants being guaranteed at method entrance. A method needs to make sure it transforms a valid state into another valid state.
方法操作现有对象,因此可以依赖于在方法入口处保证的类不变量。一个方法需要确保它将一个有效状态转换为另一个有效状态。
A constructor pulls the object out of thin air, thus must createthe invariants.
构造函数凭空拉出对象,因此必须创建不变量。
object existance
When a constructor throws an exception, the object is assumed to have never existed. Thus, e.g. a finalizer will never run. The consequences are comparedly weak in C#, they are more prominent in languages with deterministic destruction, such as C++.
对象存在
当构造函数抛出异常时,假定该对象从未存在过。因此,例如终结器永远不会运行。后果在 C# 中相对较弱,在具有确定性破坏的语言中更为突出,例如 C++。
回答by Arash Afshinfar
Note that the material of constructor is method. it means that constructor is a special type of method, its name is the same as class exactly but does not have output paramether.Constructor is called during creation of the object from class.
注意构造函数的材料是方法。这意味着构造函数是一种特殊类型的方法,其名称与类完全相同,但没有输出参数。在从类创建对象期间调用构造函数。
Public class person()
{
public person()
{
}
}
回答by user2103288
Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. Constructor needs to have the same name as that of the class whereas functions need not be the same. There is no return type given in a constructor signature (header). It is same as that of the Class There is no return statement in the body of the constructor.
创建对象时将自动调用构造函数,而必须显式调用方法。构造函数需要与类同名,而函数不必相同。构造函数签名(标头)中没有给出返回类型。和 Class 一样,构造函数体中没有 return 语句。
Example:
例子:
class Widget //Some Class "Widget"
{
int _size;
int _length;
// Declaring a Constructor, observe the Return type is not required
public Widget(int length)
{
this._length = length;
}
// Declaring a Method, Return type is Mandator
public void SomeMethod(int size)
{
this._size = size;
}
}
//Calling the Constructor and Method
class Program
{
static void Main()
{
//Calling the Constructor, Observe that it can be called at the time the Object is created
Widget newObject = new Widget(124);
//Calling the Method, Observe that the Method needs to be called from the New Object which has been created. You can not call it the way Constructor is called.
newObject.SomeMethod(10);I
}
}
回答by Ron
Constructors are special methods, used to initialize your class members with different signatures/parameters
构造函数是特殊的方法,用于初始化具有不同签名/参数的类成员