简体   繁体   中英

Run function on creation of class instance C#

I have a pice of initialiser code that should run when a new instance of a class is created, without having to be called. How would I do that ?

Update:

class Pice {

  public int Type;

  public void init() {

   Type = random(sudo);

  }

}

Now I would like the init to run only once when an instance of the class is created. So where do I put it ?

Use the class constructor.

 public class MyClass
        {
            public MyClass() 
            {
                //Initialise
            }
        }

Format this to fit your class name, paste into your class.cs file, and add your initialization logic.

public ClassName() {
    // initialization logic goes here
}

See this page for additional information.

class Pice {

 public Pice(){
  this.init();
}

  public int Type;

  public void init() {

   Type = random(sudo);

  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM