Ser*_*gel 22
构造函数仅在创建类的新实例时有效.这是在实例上运行的第一种方法,它必须运行,并且它只运行一次.
实例上的方法一旦被创建,就可以在实例上的零次到无限次之间调用.
隐式运行构造函数.创建类的新实例时,它会自动运行.方法是明确运行的.它必须从某个外部源或类中的方法 - 或构造函数 - 调用.
构造函数旨在用于布线.在构造函数中,您希望避免执行实际工作.你基本上准备要使用的类.方法旨在进行实际工作.
public class MyType
{
private SomeType _myNeeds;
// constructor
MyType(SomeType iWillNeedThis)
{
_myNeeds = iWillNeedThis;
}
// method
public void MyMethod()
{
DoSomethingAbout(_myNeeds);
}
}
Run Code Online (Sandbox Code Playgroud)
构造函数是具有特殊含义的实例方法 - 特别是在使用new创建相应类的实例时,它在内部调用.这是关键的区别.
其他一些细微差别是构造函数必须与它所属的类具有相同的名称,并且它不能具有任何返回值,甚至是void.
小智 5
创建对象时将自动调用构造函数,而必须显式调用方法.构造函数需要与类的名称相同,而函数不必相同.构造函数签名(标头)中没有给出返回类型.它与类的相同在构造函数的主体中没有return语句.
例:
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
}
}
Run Code Online (Sandbox Code Playgroud)