C#中类成员的调用

//方法 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();
    }
}

猜你喜欢

转载自blog.csdn.net/Hat_man_/article/details/105598955