C#中,实例化就是创建对象的过程,使用关键字new来创建。

    在看C#视频中遇到这么一个例子,就是更改对象的密码。我们就通过这个例子来理解一下类的创建和实例化。

    1、首先要声明一个能判断密码是否正确,并能够更改密码的类,并在类中定义相关方法。

     


  1. <span style="font-size: 18px;">    class Authentic   //声明一个判定密码是否正确,并能够更改密码的类

  2. {


  3. private string PassWord = "zhouzhou";                  //在类中定义密码


  4. public bool IsPasswordCorrect(string userPassword)      //在类中声明判断密码是否正确的方法

  5. {

  6. return (PassWord == userPassword) ? true : false;  //?:三元运算符,判断是否为真

  7. }

  8. public bool ChangePassWord(string oldPassWord, string newPassWord)//在类中声明更改密码的方法

  9. {

  10. if (oldPassWord == PassWord)

  11. {

  12. PassWord = newPassWord;

  13. return true;

  14. }

  15. else

  16. return false;

  17. }</span>


    class Authentic   //声明一个判定密码是否正确,并能够更改密码的类 
    {
                                                             
        private string PassWord = "zhouzhou";                  //在类中定义密码
        
        public bool IsPasswordCorrect(string userPassword)      //在类中声明判断密码是否正确的方法
        {
            return (PassWord == userPassword) ? true : false;  //?:三元运算符,判断是否为真
        }
        public bool ChangePassWord(string oldPassWord, string newPassWord)//在类中声明更改密码的方法
        {
            if (oldPassWord == PassWord)
            {
                PassWord = newPassWord;
                return true;
            }
            else
                return false;
        }


   2、将类实例化,如下:


  1. <span style="font-size: 18px;">    class Program

  2. {

  3. static void Main(string[] args)

  4. {

  5. Authentic simon = new Authentic(); //simon是authentic实例化的名字,类后记得加上括号

  6. bool done;

  7. done = simon.ChangePassWord("zhouzhou", "zhoujiangxiao");

  8. if (done == true)

  9. Console.WriteLine("密码已经更改");

  10. else

  11. Console.WriteLine("密码更改失败!");

  12. }

  13. }</span>


    class Program
    {
        static void Main(string[] args)
        {
            Authentic simon = new Authentic(); //simon是authentic实例化的名字,类后记得加上括号
              bool done;
            done = simon.ChangePassWord("zhouzhou", "zhoujiangxiao");
            if (done == true)
                Console.WriteLine("密码已经更改");
            else
                Console.WriteLine("密码更改失败!");            
        }
    }

   从这个例子中,很容易理解,将类实例化就是:

   类名  对象名 =  new  类名()

   3、最后介绍一下,访问修饰符对类访问的限制。如图所示:

   

   这些对编程来说,是十分基础的,但是确实十分重要的。