在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.
}
}