方法和构造函数

tin*_*tes 12 c#

我现在正在学习C#并且是编程世界的初学者.我有一本名为The Herbert Schildt的完整参考书.到目前为止它是一本好书,我正在学习方法和构造函数.

我很困惑方法和构造函数的区别.因为在书中它有几乎相同的例子.我不知道如何区分它们.我很感激你的想法.顺便说一句,我在这里有两个定义,我只想知道如何区分它们

谢谢你的帮助

干杯

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)


Chr*_*ris 15

构造函数是一种方法..一种在类的"构造"上被调用的特殊方法.

定义:构造函数是C++和C#中的类成员函数,它与类本身具有相同的名称.

构造函数的目的是在创建此类的对象时初始化所有成员变量.获取的任何资源(如内存或打开文件)通常都会在类析构函数中释放.

来自About.com


sha*_*oth 5

构造函数是具有特殊含义的实例方法 - 特别是在使用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)