C#类init函数

时间:2017-09-21 07:20:22

标签: c# python class

我正在学习c#,之前使用过python,并且我已经开始在工作中使用类了。

Python具有__init__()函数来初始化类,例如:

class name():

    __init__(self):

        # this code will run when the class is first made

c#类是否有类似的功能?

目前,我正在类中创建一个普通函数,并且必须在它生成后直接调用它。

3 个答案:

答案 0 :(得分:3)

您必须使用一个或多个构造函数: see this link on docs.microsoft.com

例如:

public class Person
{
    private string last;
    private string first;

    // This constructor is called a default constructor.
    // If you put nothing in it, it will just instanciate an object
    // and set the default value for each field: for a reference type,
    // it will be null for instance. String is a reference type, 
    // so both last and first will be null.
    public Person()
    {}

    // This constructor will instanciate an object an set the last and first with string you provide.
    public Person(string lastName, string firstName)
    {
        last = lastName;
        first = firstName;
    }
}

class Program
{
    static void Main(string[] args)
    {
       // last and first will be null for myPerson1.
       Person myPerson1 = new Person();

       // last = Doe and first = John for myPerson2.
       Person myPerson2 = new Person("Doe", "John");
    }
}

答案 1 :(得分:0)

你在c#中谈论构造函数

class MyClass{

public MyClass{ //this is the constructor equals to pythons init
}

}

这些概念几乎所有语言都有不同的格式

答案 2 :(得分:0)

你应该开始构建一个这样的构造函数:

public class Car
{
   public string plateNumber {get; set;}

   public Car(string platenumber)
   {
     this.plateNumber = platenumber;
   }
}

然后以另一种形式或类初始化它的实例:

Car myCar = new Car("123abc");