//////////////方法 1
使用的是Public,當需要調用類Book中的方法和屬性時,
需要先定義 Book book=new Book();
book.Id=1;
book.PrintMsg();
class Book
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public void SetBook(int id, string name, double price)
{
Id = id;
Name = name;
Price = price;
}
public void PrintMsg()
{
Console.WriteLine("圖書編號:" + Id);
Console.WriteLine("圖書名稱:" + Name);
Console.WriteLine("圖書價格:" + Price);
}
}
class Program
{
static void Main(string[] args)
{
Book book = new Book();
book.SetBook(1,"C#數據",12.3);
book.PrintMsg();
}
}
///////////方法 2
方法2使用修飾符 static 申明,靜態申明。
則可以直接通過類Book對其類中的方法和屬性進行操作。
Book.Id=1;
Book.PrintMsg();
class Book
{
public static int Id { get; set; }
public static string Name { get; set; }
public static double Price { get; set; }
public static void SetBook(int id, string name, double price)
{
Id = id;
Name = name;
Price = price;
}
public static void PrintMsg()
{
Console.WriteLine("圖書編號:" + Id);
Console.WriteLine("圖書名稱:" + Name);
Console.WriteLine("圖書價格:" + Price);
}
}
class Program
{
static void Main(string[] args)
{
Book.SetBook(1, "計算機基礎", 34.5);
Book.PrintMsg();
}
}