封装:Getter返回什么?

时间:2016-02-05 21:04:50

标签: c# constructor encapsulation

在Encapsulation中,get是readonly,其中set是只写

为什么我的输出在不使用特殊成员函数时是11110?

代码:

class practice_4
{
    static void Main(string[] args)
    {
        example ABC = new example();
       // ABC.Roll_ = 11;
        Console.WriteLine(ABC.Roll_ );
        Console.ReadLine();

    }
}
 class example
{
   private int roll  = 11110;
   public int Roll_
   {
       get
       {
           return roll ;
       }
       //set{
       //    if (value > 10)
       //    { roll = value; }
       //    else
       //    { Console.WriteLine("error"); }

       //}
   }
   //public example()
   //{
   //    roll = 110;
   //}

}

输出:

11110

但是当我使用特殊成员函数时:public example()

class practice_4
{
    static void Main(string[] args)
    {
        example ABC = new example();

        Console.WriteLine(ABC.Roll_ );
        Console.ReadLine();

    }
}
 class example
{
   private int roll  = 11110;
   public int Roll_
   {
       get
       {
           return roll ;
       }

   }
   public example()
   {
       roll = 110;
   }

}

所以它显示输出:

110

并弃掉11110

2 个答案:

答案 0 :(得分:1)

回答你的问题“为什么在不使用特殊会员功能时我的输出是11110?”

你班级中的特殊成员函数是你的类的构造函数,这意味着这是从你的类定义初始化/构造你的对象的特殊函数,这里要记住的规则是,构造函数是在您的私有变量语句之后调用,并且当构造函数完成时,构造完成,这意味着您的类的内部状态(变量)现在已分配(除其他外)。

但是,如果像private int roll = 11110;行一样初始化私有变量,则在调用构造函数之前执行此行。但是当你覆盖构造函数中roll的值时,私有变量的值会被覆盖。

答案 1 :(得分:0)

在示例类中,您调用的是roll变量而不是Roll_属性。如果你试图设置Roll_而不是你会得到一个编译时错误,说你不能修改只读属性。封装的目的是防止外部世界直接修改值,它不会阻止类修改值。