C# Constructor: How to Call and Use
In C#, a constructor is a special method that is automatically called when creating an instance of a class. It is used to initialize the state of the object when a new object is created.
To invoke a constructor, you just need to use the new keyword to instantiate an object and pass the necessary parameters to the constructor. For example:
public class MyClass
{
private int myValue;
// 构造函数
public MyClass(int value)
{
myValue = value;
}
public int GetMyValue()
{
return myValue;
}
}
class Program
{
static void Main()
{
// 调用构造函数来实例化对象
MyClass obj = new MyClass(10);
// 调用对象的方法
int value = obj.GetMyValue();
Console.WriteLine(value); // 输出:10
}
}
In the example above, we use new MyClass(10) to call the constructor and instantiate a MyClass object, then call the GetMyValue() method to retrieve the object’s property value.