C#:属性_赋值私有字段

C#:属性_赋值私有字段
为类中字段手写Get方法和Set方法很麻烦,
所以程序帮我们自动的封装出这个两个方法:属性

属性是这样的成员:它提供灵活的机制来读取、编写或计算某个私有字段的值。 
可以像使用公共数据成员一样使用属性,但实际上它们是称作“访问器”的特殊方法。 
这使得可以轻松访问数据,此外还有助于提高方法的安全性和灵活性。
可将属性标记为 public、private、protected、internal 或 protected internal。 
同一属性的 get 和 set 访问器可能具有不同的访问修饰符。

使用set和get方法(注意:为了数据安全性一般不会直接使用构造函数赋值私有数据,所以常见处理是使用set和get方法)

//类
 class Car
    {
    
    
        private int price;

        public int SetPrice()
        {
    
    
            if (price <= 100)
                    return price;
               else
                   return price + 1000;
        }
        public void GetPrice(int temp)
        {
    
    
            price = temp;
        }
 	}
 //main函数
 	class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Car MyCar = new Car();
            MyCar.SetPrice(1000);
            Console.WriteLine(MyCar.GetPrice());
            //Console.ReadLine();
		}
    }

输出结果:
在这里插入图片描述

属性封装了set和get方法,方便了对私有字段的处理,但二者并无本质的不同。

使用属性

//类
class Car
    {
    
    
        private int price;
        public int Price//定义属性
        {
    
    
            get
            {
    
    
                if (price <= 100)
                    return price;
                else
                    return price + 1000;
            }
            set
            {
    
    
                price = value;
            }
        }
        private string name;
        public string Name {
    
     get; set; }//属性的一种简写方式
    }
//main函数    
class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Car MyCar = new Car();
            MyCar.Price = 1000;
            Console.WriteLine(MyCar.Price);
            MyCar.Name = "程序员";
            Console.WriteLine(MyCar.Name);
            //Console.ReadLine();
         }
    }

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43269758/article/details/108564705