google0312 发表于 2016-8-1 11:46:53

C#入门基础——属性

       属性:在类中有些字段是共有的,有些字段是私有的,共有的能访问到的,但是私有的在别的类中就访问不到了,但是我们还要用到私有字段,怎么办呢,这个时候就用到了属性这个概念,用属性来完成这项任务,而属性又能读取又能写入,更加符合我们的要求。

namespace 属性实例
{
    class Program
    {
      static void Main(string[] args)
      {
            C1 c = new C1();
            Console.WriteLine("myValue: {0}",c.MyValue);
         c.MyValue = 20;
            Console.WriteLine("myValue: {0}",c.MyValue);
            Console.ReadKey();
      }
    }
    class C1
    {
      private int theRealValue = 10;
      public int MyValue
      {
            set { theRealValue=value; }   //set访问器为属性赋值
            get { return theRealValue; }//get访问器从属性读取值
      }
    }
}

输出结果:
myValue:   10
myValue:   20

match123_xbd 发表于 2023-4-3 17:39:19

{:5_106:}
页: [1]
查看完整版本: C#入门基础——属性