在C#中,创建一个实例通常涉及以下几个步骤:
Person
的类:public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void SayHello()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
new
关键字来创建一个类的实例。在这个例子中,我们将创建一个名为person1
的Person
类实例:Person person1 = new Person();
person1
实例的属性设置值:person1.Name = "John Doe";
person1.Age = 30;
person1
实例的方法:person1.SayHello(); // 输出: Hello, my name is John Doe and I am 30 years old.
将以上代码放在一起,完整的示例如下:
using System;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void SayHello()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.Name = "John Doe";
person1.Age = 30;
person1.SayHello(); // 输出: Hello, my name is John Doe and I am 30 years old.
}
}