在C#中,实例化是创建类的对象或实例的过程。通过实例化,我们可以使用类的成员变量、方法和属性,并对其进行操作。
// 定义一个类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// 实例化对象
Person person = new Person();
person.Name = "John";
person.Age = 25;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// 带参数的构造函数
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
// 实例化对象并初始化
Person person = new Person("John", 25);
public class Car
{
public string Brand { get; set; }
public string Model { get; set; }
public void StartEngine()
{
// 启动引擎的逻辑
}
}
// 实例化多个Car对象
Car car1 = new Car();
car1.Brand = "Toyota";
car1.Model = "Camry";
Car car2 = new Car();
car2.Brand = "Honda";
car2.Model = "Civic";
public class Circle
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
// 实例化对象并使用引用访问成员
Circle circle = new Circle();
circle.Radius = 5.0;
double area = circle.CalculateArea();
Console.WriteLine("Circle area: " + area);
public class MyClass
{
public MyClass()
{
Console.WriteLine("Object created.");
}
~MyClass()
{
Console.WriteLine("Object destroyed.");
}
}
// 实例化对象
MyClass obj = new MyClass();
// 执行其他操作...
obj = null; // 设置对象为 null,不再引用它
// 在适当的时候,垃圾回收器会回收对象并调用析构函数