类中的get,set 权限理解

70 阅读1分钟

在看一些开源项目或一些博客时,发现一些类属性设置是各种不一样的,于是自己停下来做了一个小小的实践,验证下自己的理解。

代码

   public class DemoTest
    {

        public int Id { get; } //只能在构造函数里赋值

        public string Name { get; set; }

        public string Description { get; private set; }//只能在内部赋值

        public DemoTest()
        {
            this.Id = 100;
            this.Name="Test";
            this.Description= "DesTest";
        }
        public DemoTest(int id,string name,string des)
        {
            this.Id = id;
            this.Name = name;
            this.Description = des;
        }

        public void run()
        {
            this.Name = "内部赋值demo";
          // this.Id++;
            this.Description="内部赋值DecemberTest";
        }
    }

测试代码

            DemoTest tx = new DemoTest();
            Console.WriteLine(tx.Id);
            Console.WriteLine(tx.Name);
            Console.WriteLine(tx.Description);

            Console.WriteLine("==============================");

            DemoTest tx2 = new DemoTest(99,"大家好","我是测试");
            Console.WriteLine(tx2.Id);
            Console.WriteLine(tx2.Name);
            Console.WriteLine(tx2.Description);
            Console.WriteLine("==============================");
            // tx.Id = 10;//外部赋值是不行的
            tx.Name="NewTest";
          //  tx.Description = "Des"; tx.Id = 10;//外部赋值是不行的

结果

image.png

得出结论: get 可以赋值,但是只能在构造函数里传值,可以任意取值 get,set 可以在任何地方赋值取值 get; private set;表示能在类内部赋值和构造函数里传值。