2017-09-21 6 views
-3

私はC#を学んでいます。以前はpythonを使っていましたが、私は自分の仕事でクラスを使い始めました。C#classes init関数

Pythonは、たとえば、クラスを初期化する__init__()機能を持っています

class name(): 

    __init__(self): 

     # this code will run when the class is first made 

は、C#クラスの同様の機能はありますか?

現在、私はクラス内に通常の関数を作成しており、作成後に直ぐに呼び出す必要があります。 see this link on docs.microsoft.com:C#でコンストラクタについて

+1

コンストラクタやオブジェクト・イニシャライザについて読んだことがありますか?ほんのいくつかの研究が良いでしょう。 – HimBromBeere

+1

[MSDN](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes)を参照してください。 –

答えて

3

で、ほぼすべての言語でご利用いただけます。例えば

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"); 
    } 
} 
0

あなたの話は

class MyClass{ 

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

} 

これらの概念は、異なるフォーマットあなたはそのために1つ以上のコンストラクタを使用する必要が

0

あなたはこのようなコンストラクタ構築を開始する必要があります。

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

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

をそして、そのような別のフォームまたはクラスでのインスタンスを初期化します。

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