------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------
万物皆对象
属性:事物所具有的各种特征,每个属性都有特定的值 方法:事物的行为、动作
对象:实实在在存在的东西
类:类是模子,确定对象将会拥有的特征(属性)和行为(方法)
类是抽象的概念,仅仅是模板。
对象可以叫做类的实例化。
类不占内存,因为只是概念;对象就要占内存
类的定义 [访问修饰符] class 类名 { 成员; ......
}
类中可以包含变量和方法
通过类来产生一个对象的过程,叫做类的实例化。用new关键字 语法:类名 实例名 = new 类名();
using System; using System.Collections.Generic; using System.Text; namespace 面向对象 { class Program { static void Main(string[] args) { /*关于static * * 1.没加static的方法或变量,要new实例化以后,通过实例名.方法或实例名.变量来访问 * * 2.加了static的方法或变量,可以直接用类名.方法名或类名.变量名来访问 * ------------------------------------------------------------------------------- * 关于访问修饰符 * 1.public 可以在任何地方被访问 * * 2.private 只能在本类中被访问 (在类里,方法外包含方法 不写访问修饰符,默认为private) * * 3.internal 只能在项目中被访问 * * 4.protected 只能在本类或子类中被访问 * */ #region 学习对象 //类的实例化成对象 Person zsPerson = new Person(); Person lsPerson = new Person(); //对象的属性 //通过实例名(对象名).属性名访问 zsPerson.Name = "张三"; zsPerson.Sex = '男'; zsPerson.Age = 18; lsPerson.Name = "李四"; lsPerson.Sex = '女'; lsPerson.Age = -20; //对象的方法 //通过实例名(对象名).方法名()访问 lsPerson.SayHello(); zsPerson.SayHello(); #endregion #region 作业 //Student zsStudent = new Student();//声明zsStudent并实例化 //zsStudent.Name = "";//开始为属性赋值 //zsStudent.Sex = '男'; //zsStudent.Age = 18; //zsStudent.Chinese = 90; //zsStudent.Math = 95; //zsStudent.English = 80; //zsStudent.SayHello();//调用方法 //zsStudent.Score(); //Console.WriteLine(); //Student xlStudent = new Student(); //xlStudent.Name = "小兰"; //xlStudent.Sex = '女'; //xlStudent.Age = 16; //xlStudent.Chinese = 95; //xlStudent.Math = 85; //xlStudent.English = 100; //xlStudent.SayHello(); //xlStudent.Score(); #endregion //Student stu = new Student("皮蛋", 18,'男'); //stu.SayHello(); Console.ReadKey(); } } }
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace 面向对象 6 { 7 //类的定义语法 8 /*[访问修饰符] class 类名 9 * { 10 * 成员; 11 * } 12 * 成员有属性和方法 13 * 14 * 类的实例化 15 * 语法:类名 实例化名 = new 类名(); 16 * */ 17 class Person 18 { 19 //允许外部访问的变量一定要声明为属性 20 //属性的作用在于保护相应字段,保证起合法性 21 /* 22 * 三种属性 23 *1.具有get set方法 叫读写属性 24 *2.只具有 set 的方法的属性 叫只写属性 ,只能写不能读(不常用) 25 *3.只具有get 只能读,不能写 叫只读属性 26 * 27 * */ 28 29 //3个字段 30 private string name; 31 32 //定义一个变量,里面含有get/set方法,这个就叫属性 33 public string Name 34 { 35 get { return name; } 36 set 37 { 38 if (value == "皮蛋") 39 { 40 name = "匿名"; 41 } 42 else 43 { 44 name = value; 45 } 46 } 47 } 48 49 private char sex; 50 51 public char Sex 52 { 53 get { return sex; } 54 set 55 { 56 if (value == '男') 57 { 58 sex = value; 59 } 60 else if (value == '女') 61 { 62 sex = value; 63 } 64 else 65 { 66 sex = '中'; 67 } 68 } 69 } 70 71 private int age; 72 73 public int Age 74 { 75 get { return age; } 76 set 77 { 78 if (value >= 0) 79 { 80 age = value; 81 } 82 else 83 { 84 age = 0; 85 } 86 } 87 } 88 89 public void SayHello() 90 { 91 Console.WriteLine("我叫{0},我是{1}生,我今年{2}岁了。", name, sex, age); 92 } 93 } 94 }