C#面向对象——成员变量及封装
namespace 面向对象5_22 { class Animal { private string _Type; public string Type { get { return _Type; } set { _Type = value; } } private string _Food; public string Food { //读取 get { /*这是函数体,可以写任何内容,然后是可以通过return把值传出去,return出去的值的数据类型是根据以前定义的数据类型来决定的*/ return _Food; } //写入 set { if(value=="肉") { _Food ="我是羊,不吃肉"; } } } private int _Name; public int Name { get { //取值 int sum = 5; return sum; } set { _Name = value; }//赋值 先执行set 再执行get } private string _bianliang1; public string Bianliang1 { get { return _bianliang1; } set { _bianliang1 = value; } } public string bianliang2; } }
namespace 面向对象5_22 //命名空间 { class Student //用户自定义数据类型 { public string code;//成员变量 public string name;//public是修饰符 private ,protected, interval 它们代表的是作用范围 public string sex;//用处:可以在当前类作为外部变量来使用;可以作为类的个体的一个参数来使用 public int sum; public void jiafa() { sum = sum+3; } public void jianfa() { sum = sum-5; } } class Program //用户自定义数据类型 { static void Main(string[] args) { Student s = new Student(); //s就是一个对象(一个Student类型的对象) s.code = "1001"; s.name = "幻觉"; Console.WriteLine(s.sum); s.jiafa(); Console.WriteLine(s.sum); s.jianfa(); Console.WriteLine(s.sum); Student s1=new Student(); s1.jianfa(); Console.WriteLine(s1.sum); Animal adata = new Animal(); adata.Food = "肉"; Console.WriteLine(adata.Food); adata.bianliang2 = "肉"; Console.WriteLine(adata.bianliang2); adata.Name = 1; Console.WriteLine(adata.Name); Console.ReadLine(); } } }