1.函数
1.函数 /// <summary> /// main /// 主函数(主方法)控制台的输出输入控制函数 /// </summary> /// <param name="args">字符串参数</param> static void Main(string[] args) //static 静态修饰符,void(int,string char)是无返回值+方法名(参数){ 方法体} { int num1 = int.Parse(Console.ReadLine()); int num2 = int.Parse(Console.ReadLine()); string num3= GetMax(num1, num2); Console.WriteLine(num3); //Run(); //ChangeSelf(); //Run(); //ChangeSelf(); //int num1 = 10; //Console.WriteLine(num1); //return ; //结束当前方法 //int num2 = 20; //Console.WriteLine(num2); } public static string GetMax(int num1,int num2) { int num3 = num1 > num2 ? num1 : num2; //Console.WriteLine(num3); return num3+""; } public static void Run() { Console.WriteLine("超级玛丽,跑啊跑,跳啊跳"); Console.WriteLine("超级玛丽,跑啊跑,跳啊跳"); Console.WriteLine("超级玛丽,跑啊跑,跳啊跳"); Console.WriteLine("超级玛丽,跑啊跑,跳啊跳"); Console.WriteLine("超级玛丽,跑啊跑,跳啊跳"); } public static void ChangeSelf() { Console.WriteLine("遇见一个砖块,撞一下无敌"); Console.WriteLine("屏幕闪烁,身体变大"); Console.WriteLine("遇到小怪,无敌消失"); }
例子1: public static int a = 3; static void Main(string[] args)//void 无返回值 { // int a = 3; Text(); Console.WriteLine(a);//作用域不同产生的结果不同 } public static void Text() { a = a + 5; }
例子2: Console.WriteLine("请输入年份"); string s = Console.ReadLine(); year= IsInt(s); bool b= IsRun(year); Console.WriteLine("{0}是闰年吗?{1}", year, b); } public static int IsInt(string s) { int year; while (true) { try { year = int.Parse(s); return year; } catch { Console.WriteLine("您输入的有误,请在输入一次"); s = Console.ReadLine(); } } } public static void Text() { a = a + 5; } public static bool IsRun(int year) { bool b = year % 400 == 0 || year % 4 == 0 && year % 100 != 0; return b; }
例子3: //利用方法求两个数的和与积 int num1 = 20; int num2 = 30; int[] s= GetSum(52,63);//实参 Console.WriteLine("和为{0},积为{1}",s[0],s[1]); } public static int[] GetSum(int a, int b)//形参,变量名字与main的变量名字没有任何关系 { //Console.WriteLine("和为" + (num1 + num2)); //Console.WriteLine("积为" + (num1 * num2)); int sum = a + b; int[] nums = { sum, (a * b) }; return nums; }
例子4: int[] nums = {10,54,63,55,45,65,23,54,33,65,46 }; int[] n= GetResult(nums); foreach (var item in n) { Console.WriteLine(item); } } public static int[] GetResult(int[] nums) { int sum = 0; int avg = 0; int min = nums[1]; int max=nums[5]; for (int i = 0; i < nums.Length; i++) { if (nums[i]>max) { max = nums[i]; } if (nums[i]<min) { min = nums[i]; } sum += nums[i]; } avg = sum / nums.Length; int[] n = { max,min,sum,avg}; return n; }
using System; namespace _002_函数 { class Program { static void Main(string[] args) { int year; Console.WriteLine("请输入年份"); string s = Console.ReadLine(); year = IsInt(s); bool b = IsRun(year); Console.WriteLine("{0}是闰年吗?{1}",year,b); } public static int IsInt(string s) { int year; while (true) { try { year = int.Parse(s); return year; } catch { Console.WriteLine("输入有误,请重新输入"); s = Console.ReadLine(); } } } public static bool IsRun(int year) { bool b = year % 400 == 0 || year % 4 == 0 && year % 100 != 0; return b; } } }
using System; namespace _006_作业3 { class Program { static void Main(string[] args) { Console.WriteLine("请输入用户名和密码:"); string name = Console.ReadLine(); string mima = Console.ReadLine(); int password = IsInt(mima); Name(name,password); } #region 判断密码 public static int IsInt(string mima) { while (true) { int password = 0; try { password = int.Parse(mima); return password; } catch { Console.WriteLine("密码输入有误,请重新输入"); mima = Console.ReadLine(); } } } #endregion #region 判断用户名和密码 public static void Name(string name,int password) { int i = 1; while (i < 5) { if (name == "admin" && password == 123456) { Console.WriteLine("登录成功"); break; } else { Console.WriteLine("密码或用户名错误,请重新输入"); name = Console.ReadLine(); string mima = Console.ReadLine(); password = IsInt(mima); } i++; } } #endregion } }
using System; namespace _007_作业4_菲波那切数列 { class Program { static void Main(string[] args) { int a = 0; int b = 1; int index = SS(a, b); Console.WriteLine("斐波那数列第十个数为"+index); } public static int SS(int a,int b) { int c = 0; for (int i = 1; i < 9; i++) { c = a + b; a = b; b = c; } return c; } } }
using System; namespace _008_作业5_比较三个数大小 { class Program { static void Main(string[] args) { Console.WriteLine("请输入三个数"); int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); int c = int.Parse(Console.ReadLine()); IsInt(a, b, c); } public static void IsInt(int a,int b,int c) { int max = a > b ? a : b; max = max > c ? max : c; int min = a < b ? a : b; min = min < c ? min : c; int zj = (a + b + c) - max - min; Console.WriteLine("最大值为"+max+"中间值为"+zj+"最小值为"+min); } } }
using System; namespace _009_作业6_计算器 { class Program { static void Main(string[] args) { Console.WriteLine("请输入要进行的计算,和数字"); string c = Console.ReadLine(); PanDuanFuHao(c); } #region 判断运算符 public static void PanDuanFuHao(string c) { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); switch (c) { case "+": JF( a,b); break; case "-": JianF(a, b); break; case "*": CF(a, b); break; case "/": ChuF(a, b); break; default: Console.WriteLine("请重新输入"); break; } } #endregion #region 加 public static void JF(int a,int b) { Console.WriteLine("和为"+(a+b)); } #endregion #region 减 public static void JianF(int a, int b) { Console.WriteLine("差为" + (a - b)); } #endregion #region 乘 public static void CF(int a, int b) { Console.WriteLine("积为" + (a * b)); } #endregion #region 除 public static void ChuF(int a, int b) { Console.WriteLine("商为" + (a / b)); } #endregion } }
2.
函数的重载
构成重载的条件:
1.方法名必须一样,参数列表不同(参数类型不同,参数个数不同)
2.与返回值无关
static void Main(string[] args) { Sum(10,20); //方法构成重载的条件:1.方法名必须一样,参数列表不同(参数类型不同,参数个数不同)2.与返回值无关 Console.WriteLine(); } public static void Sum(int num1, int num2) { Console.WriteLine(num1 + num2); } public static int Sum(int num3, int num4,int num5) { return num3 + num4 ; } public static string Sum(int a, bool b) { return ""; } public static void Sum(int num6, string num7) { Console.WriteLine(num6+int.Parse(num7)); }
using System; namespace _014_函数的重载 { class Program { public static int MaxValue(params int[] arry) { int maxvalue = arry[0]; for (int i = 1; i < arry.Length; i++) { if (arry[i] > maxvalue) { maxvalue = arry[i]; } } return maxvalue; } public static double MaxValue(params double[] arry) { double maxvalue = arry[0]; for (int i = 1; i < arry.Length; i++) { if (arry[i] > maxvalue) { maxvalue = arry[i]; } } return maxvalue; } static void Main(string[] args) { int res = MaxValue(123, 25, 63); double res1 = MaxValue(3.14, 2.28, 56.3); Console.WriteLine(res1); } } }
例子:ref static void Main(string[] args) { //ref int num = 20; int num1 = 30; int sum=0; Sum(ref sum, num, num1);//ref:把实参中的值带入形参参与运算,运算完毕赋值再带出来(ref的值必须赋予初值) Sum(ref num,ref num1); Console.WriteLine(num+" "+num1); } public static void Sum(ref int sum, int num, int num1) { sum = num + num1; } public static void Sum(ref int a,ref int b) { int sum = a + b; a = a > b ? a : b; b = sum - a; }
using System; namespace _015_ref { class Program { static void Main(string[] args) { int num1 = 10; int num2 = 50; MaxValue(ref num1,ref num2);//把实参的值带入形参参与运算,运算wanbi 赋值在带出来(ref值必须赋予初值) Console.WriteLine(num1+" "+num2); } public static void MaxValue( ref int num1, ref int num2) { int sum = num1+num2; num1 = num1 > num2 ? num1 : num2; num2 = sum - num1; } } }
例子:out Console.WriteLine("请输入数字"); string num = Console.ReadLine(); int number; bool b= TryPase(num,out number); if (b) { Console.WriteLine(number); } else { Console.WriteLine(num); } } public static bool TryPase(string num,out int number) { number = 0; try { number = int.Parse(num); return true; } catch { return false; } }
using System; namespace _016_out { class Program { static void Main(string[] args) { int a = 12; int b = 2; Sum(out a, out b); Console.WriteLine(a + " " + b); } public static void Sum(out int a, out int b) { a = 100; b = 12; a = a + b; } } }
using System; namespace _018_out求和_平均值_ { class Program { static void Main(string[] args) { int[] num = { 12, 25, 33, 42, 36 }; Max(num, out int sum, out double average, out int max, out int min); Console.WriteLine(sum+" "+average+" "+max+" "+min); } public static void Max(int[]num1,out int sum,out double average,out int max,out int min) { sum = 0; max = int.MinValue; min = int.MaxValue; average = 0; for (int i = 0; i < num1.Length; i++) { if (num1[i] > max) { max = num1[i]; } if (num1[i] < min) { min = num1[i]; } sum += num1[i]; } average = sum / num1.Length; } } }
3.函数的递归
using System; namespace _010_函数的递归调用 { class Program { public static int F(int n) { if (n == 0) return 2; if (n == 1) return 3; return F(n - 1) + F(n - 2); } static void Main(string[] args) { //f(n)=f(n-1)+f(n-2) f(0)=2 f(1)=3 ,用程序求得f(40) int res = F(40); Console.WriteLine(res); } } }
public static int i = 0; static void Main(string[] args) { //递归:自己的方法调用自己的方法就是递归 //int num=0; //SayStory(); //用递归求100以内正数的和 int num = 100; int sum = GetSum(100);// getSumDG(99)+100//getSumDG(98)+99+100 sum = GetSum(99) + 100; sum = (GetSumDG(98) + 99) + 100; sum = (GetSumDG(97) + 98) + 99 + 100; } public static int GetSumDG(int i) { if (i == 1) { return 1; } return GetSumDG(i - 1) + i; // getSumDG(99)+100 //getSumDG(98)+99+100 // ..... // GetSumDG(1)+2+...+100 } public static int GetSum(int i) { int sum = 0; //for (i = 1; i <= 100; i++) //{ // sum += i;// 1+2+3+4+5+6....+99+100 //} for (i = 100; i > 0; i--) { sum += i;//100+99+98+97+.....3+2+1 } return sum; } public static void SayStory() { // int i = 0; if (i == 3) { return; } i++; Console.WriteLine("从前山里有个庙"); Console.WriteLine("庙里有个老和尚跟一个小和尚"); Console.WriteLine("老和尚给小和尚讲故事"); Console.WriteLine("两个和尚没水喝"); SayStory(); } public static void SayStory(int i) { // int i = 0; if (i == 3) { return; } i += 1; Console.WriteLine("从前山里有个庙"); Console.WriteLine("庙里有个老和尚跟一个小和尚"); Console.WriteLine("老和尚给小和尚讲故事"); Console.WriteLine("两个和尚没水喝"); SayStory(i); }
using System; namespace _012阶乘 { class Program { public static int JC(int n) { int res = 1; for (int i = 1; i <= n; i++) { res *= i; } return res; } static void Main(string[] args) { int jc = 1; int sum = 0; for (int i = 1; i <= 20; i++) { //求1+2!+3!+...+20!的和? //jc = jc * i; //sum += jc; sum += JC(i); } Console.WriteLine(sum); } } }
1.
using System; namespace _013_判断质数 { class Program { static void Main(string[] args) { // 要求:重复让用户输入一个数,判断该数是否是质数,输入q结束? 质数的判断用方法来实现bool IsPrime(int number) //输入2时有bug Console.WriteLine("请输入一个数(输入q退出):"); string str = Console.ReadLine(); while (str != "q") { int num; while (!int.TryParse(str, out num)) { Console.WriteLine("你刚刚输入的不是一个数字,请重新输入(输入q,退出):"); str = Console.ReadLine(); if (str == "q") { return; } } //if(num == 1) //{ // Console.WriteLine("1不是质数"); // str = Console.ReadLine(); //} bool result = IsPrime(num); //调用方法,判断是否为质数 if (result) { Console.WriteLine("{0}是质数", num); str = Console.ReadLine(); } if (result == false) { Console.WriteLine(num+"不是质数,请再输入一个数(q退出)"); str = Console.ReadLine(); } } Console.ReadKey(); } public static bool IsPrime(int number) { bool result = false; for (int i = number - 1; i >1; i--) { if (number % i == 0) //如果能整除,则不是质数 { result = false; } if (number % i != 0)//是质素 { result = true; } } return result; //注意return的位置,如果写在for 循环内,发生错误,不能----“返值” } } }
static void Main(string[] args) { //重复让用户输入一个数,判断该数是否是质数,输入q结束?质数的判断用方法来实现bool IsPrime(int number) Console.WriteLine("请输入一个数字"); string num = Console.ReadLine(); GetZS(num); } public static void GetZS(string num) { while (true) { if (num == "q") { break; } else { IsPrime(GetNum(num)); num = Console.ReadLine(); } } } public static int GetNum(string s) { while (true) { try { int num = int.Parse(s); return num; } catch { Console.WriteLine("您输入有误,重新输入"); s = Console.ReadLine(); } } } public static bool IsPrime(int num) { for (int i = 2; i <= num; i++) { if (num % i == 0 && num != i) { Console.WriteLine("不是质数"); return false; } else if (i == num) { Console.WriteLine("是质数"); return true; } } return false; }
4.try.pase
using System; namespace _017_try.pase { class Program { static void Main(string[] args) { Console.WriteLine("请输入账号和密码"); string name = Console.ReadLine(); string password = Console.ReadLine(); string massage; Name(name, password, out massage); Console.WriteLine(massage); } public static void Name(string name ,string password,out string massage) { massage = ""; if (name == "admin" && password == "123456") { massage = "登录成功"; } else { massage = "失败"; } } public static bool TryPase(string num,out int number) { number = 0; try { number = int.Parse(num); return true; } catch { return false; } } } }
5.面向对象
using System; using System.Collections.Generic; using System.Text; namespace _001_面向对象 { public class People { private string _name; public int _age; private char _sex; public char Sex { get { return _sex; } set { if (value != '男' && value != '女') { value = '中'; } _sex = value; } } public int Age { get { return _age; } set { if (value < 0 || value > 100) { value = 0; } _age = value; } } public People(string name, int age) //构造函数,用于构造对象,如果类里面没有该无参构造函数,就系统默认调用一个无参的构造函数 { //只要自己定义了一个构造函数,系统中默认的无参的构造函数就不存在了 this.Name = name;//构造函数结构,public+类名+(){} ,无返回值,void都没有 this.Age = age; } public People() //构造函数是可以构成重载的 { } public People(string name, int age, char sex) { this.Name = name; this.Age = age; this.Sex = sex; } public string Name { get { return _name; } set { if (value != "张三") { value = "张三"; } _name = value; } } public void CHLSS() { Console.WriteLine("{0}今年{1}岁了,性别{2},可以吃喝拉撒睡", this.Name, this.Age, this.Sex); } } }
using System; namespace _001_面向对象 { class Program { static void Main(string[] args) { People zsPeople = new People("李四", 20, '女');//类的实例化,new的作用开辟一个内存 zsPeople.CHLSS(); //类:这个类具有所有人类的特性,是把对象中的共同点进行提炼抽象化出来的类 //对象:类实例化出来的,他是实际存在的, //public 公共的,外界可以调用 //private 私有的,只能在本类中调用 //zsPeople.Age = 15; //zsPeople.Sex = 'a';//对象的初始化 //zsPeople.Name = "张"; //zsPeople.CHLSS(); Console.ReadKey(); } } }
using System; namespace _002集合 { class Program { static void Main(string[] args) { _Student hwPeople = new _Student("黄伟",96,88,64); hwPeople.ZWJS(); } } }
using System; using System.Collections.Generic; using System.Text; namespace _002集合 { public class _Student { public string _name; public char _sex; public int _age; public double _chinese; public double _math; public double _English; public double _Sum; public double _Average; public string Name { get { return _name; } set { _name = value; } } public char Sex { get { return _sex; } set { _sex = value; } } public int Age { get { return _age; } set { _age = value; } } public double Chinese { get { return _chinese; } set { _chinese = value; } } public double Math { get { return _math; } set { _math = value; } } public double English { get { return _English; } set { _English = value; } } public _Student(string name, double chinese, double math, double English) { this.Name = name; this.Chinese = chinese; this.Math = math; this.English = English; } public void ZWJS() { //Console.WriteLine("我叫{0},今年{1}岁了,是{2}同学",this.Name,this.Age,this.Sex); double sum = 0; sum = this.English + this.Chinese + this.Math; double average = sum / 3; Console.WriteLine("我叫"+this.Name+ "这次总成绩是"+sum +"分,平均成绩是"+average); } } }
using System; using System.Collections.Generic; using System.Text; namespace _004_Ticket { class Ticket { private int _distance; private double _price; private int Distance { get { return _distance; } set { if (value < 0) { value= 0; } _distance = value; } } private double Price { get { return _price; } set { if (_distance > 101 && _distance < 200) { value = value * 0.95; } if (_distance > 201 && _distance < 300) { value = value * 0.9; } if (_distance > 300) { value = value * 0.8; } _price = value; } } public Ticket(int distance,double price) { this.Distance = distance; this.Price = price; } public void JiaGe() { double jiage = 0; jiage = this.Price * this.Distance; Console.WriteLine(this.Distance+"公里"+jiage+"块钱"); } } }
using System; namespace _004_Ticket { class Program { static void Main(string[] args) { Ticket Get = new Ticket(90, 1); Get.JiaGe(); } } }
6.
字符串
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _001_字符串 { class Program { static void Main(string[] args) { //string a = "huangwei";//我们使用string类型去存储字符串类型,字符串 需要使用双引号引起来 //int length = a.Length;//通过length获取字符串长度,空格也属于字符 //Console.WriteLine(length); //char s = a[0];//通过索引取得字符串中的字符 //a = "http://" + a;//字符串的链接 //bool b =a.Contain("w");//是否包含某个字符串 //a=a.Insert(2,"514")//在指定位置插入字符串 //for (int i = 0; i < a.Length; i++) //{ // Console.WriteLine(a[i]);//字符串的遍历 //} //int res = a.CompareTo("hiangwei"); //当两个字符串相等的时候,返回0, // int index= s.IndexOf('4');//查找当前元素所在索引,查找到第一个索引为其元素时停止 //string str = a.Replace('h', 'H');//把指定的字符换成指定的字符 //string str1 = a.Replace("huang","HUANG");//把指定字符串换成指定字符串 //Console.WriteLine(str); //Console.WriteLine(str1); // string s = "www.baidu.com"; //s= s.Substring(index+1);//截取字符串包含当前索引的值 // string s= str.Clone().ToString();//克隆一个字符串变成object类型,我们强转成字符串, //(一切类型+.ToString()都会变成字符串) // Console.WriteLine(index); //int num = 123; //string s = num.ToString(); //bool b= string.IsNullOrEmpty(str); //bool bb= str.EndsWith('a'); //bool bbb=str.StartsWith('a'); //string[] array = s.Split('.');//以指定字符拆分成字符串数组 // foreach (var item in array) // { // Console.WriteLine(item); // } // s = string.Join("|", array); // Console.WriteLine(s);//把字符串数组中添加一个字符把其串联成一个新的字符串 //string str = s.Substring(4, 5);//按指定索引位置开始取子字符串,后面不写,表示 去到最后 //Console.WriteLine(str); //string s = "huangWEI";//所有字符转换为小写形式 //string str = s.ToLower(); //String str1 = s.ToUpper();//所有字符转换为大写 //Console.WriteLine(str); //string s = "www.baidu.com"; //string str = s.Trim();//删除两端的空白 //Console.WriteLine(str); //int index = s.IndexOf("baidu");//判断当前字符串是否包含一个子字符串,如果不包含,则返回-1,如果包含,会返回第一个字符的索引 //Console.WriteLine(index); //string s = "huangwwei"; //s = s.Remove(5, 2); //Console.WriteLine(s);//从当前索引删除指定长度字符串 } } }
stringBulider: string s = "123";//每次赋值都会重新申请内存 StringBuilder ss = new StringBuilder();//效率很快,只需要一片内存 ss.Append("123"); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100000; i++) { s += i;//00:00:10.3843778 // ss.Append(i);//00:00:00.0111952 } sw.Stop(); // Console.WriteLine(ss.ToString()); Console.WriteLine(s); Console.WriteLine(sw.Elapsed); //bool b= string.IsNullOrEmpty(str); //bool bb= str.EndsWith('a'); //bool bbb=str.StartsWith('a');
7.继承
class Program { static void Main(string[] args) { // Teacher t = new Teacher();//继承的好处:把具有相同特征的类的重复的方法和属性提炼到一个类里面,省略冗余代码 Student s = new Student("张三", 30);//子类继承于父类,拥有父类的一切特征,创建对象时要走一遍父类的构造函数,子类不能继承父类的构造函数 //s.Name = "张三"; //s.Age = 20; //s.Sex = '男'; s.Study1(); // Driver d = new Driver(); // Person p = new Person(); // p.Say(); } } public class Person { private string name; private int age; private char sex; public Person(string name, int age, char sex) { Name = name; Age = age; Sex = sex; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } public char Sex { get => sex; set => sex = value; } public void Say() { Console.WriteLine("我是人类"); } } public class Teacher : Person { //private string name; //private int age; //private char sex; //public string Name { get => name; set => name = value; } //public int Age { get => age; set => age = value; } //public char Sex { get => sex; set => sex = value; } public Teacher(string name, int age, char sex) : base(name, age, sex) { } public void Teach() { Console.WriteLine("老师叫{0},今年{1}岁了,性别{2},他会教书", Name, Age, Sex); } } public class Student : Person { private int _id; //private string name; //private int age; //private char sex; //public string Name { get => name; set => name = value; } //public int Age { get => age; set => age = value; } //public char Sex { get => sex; set => sex = value; } public Student(string name, int age, char sex, int id) : base(name, age, sex) { //Name = name; //Age = age; //Sex = sex; this.Id = id; } public Student(string name,int id):base(name,0,'a') { this.Id = id; } public void Study1() { Console.WriteLine("我叫{0}。我的学号是{1}",Name,this.Id); } public int Id { get => _id; set => _id = value; } public void Study() { Console.WriteLine("学生叫{0},今年{1}岁了,性别{2},学号{3},他会学习", Name, Age, Sex, this.Id); } } public class Driver : Person { //private string name; //private int age; //private char sex; //public string Name { get => name; set => name = value; } //public int Age { get => age; set => age = value; } //public char Sex { get => sex; set => sex = value; } public Driver(string name, int age, char sex) : base(name, age, sex) { //Name = name; //Age = age; //Sex = sex; } public void Drive() { Console.WriteLine("司机叫{0},今年{1}岁了,性别{2},他会开车", Name, Age, Sex); } }
例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _004继承习题 { class Program { static void Main(string[] args) { Programmer s = new Programmer("黄伟",22,10); s.Jc1(); Reproter a = new Reproter("谭红", 52, "吃翔"); a.JS(); } } public class Person { private string name; private int age; public Person(string name,int age) { Name = name; Age = age; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } } public class Reproter : Person { private string aihao; public Reproter(string name, int age, string aihao):base(name,age) { this.Aihao = aihao; } public void JS() { Console.WriteLine("大家好,我叫{0},今年{1}岁,我的爱好是{2}", Name, Age, this.aihao); } public string Aihao { get => aihao; set => aihao = value; } } public class Programmer : Person { private int time; public Programmer(string name, int age, int time):base(name,age) { this.time = time; } public void Jc1() { Console.WriteLine("大家好,我叫{0},今年{1},我已经工作{2}年了", Name, Age, this.time); } public int Time { get => time; set => time = value; } } }
继承随机生成:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _005继承随机 { class Program { static void Main(string[] args) { int num = 0; Person[] ps = { new Student(), new Teacher(), new Beauty(), new Animal(), new Ren() }; Random random = new Random();//注意!!!别放里面 for (int i = 0; i < 10; i++) { num = random.Next(0, 5); //for (int j = 0; j < 10; j++) //{ if (ps[num] is Student) { Student psStudent = (Student)ps[num]; psStudent.GetStudent(); continue; } else if (ps[num] is Teacher) { Teacher psTeacher = (Teacher)ps[num]; psTeacher.GetTeacher(); continue; } else if (ps[num] is Beauty) { Beauty psBeauty = (Beauty)ps[num]; psBeauty.GetBeauty(); continue; } else if (ps[num] is Animal) { Animal psAnimal = (Animal)ps[num]; psAnimal.GetAnimal(); continue; } else if (ps[num] is Ren) { Ren psRen = (Ren)ps[num]; psRen.GetPerson(); continue; } else { Console.WriteLine("转不了"); break; } //} } } } public class Person { private string name; private int age; public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } } public class Ren : Person { public void GetPerson() { Console.WriteLine("我是人类"); } } public class Man : Person { public void GetMan() { Console.WriteLine("我是帅哥"); } } public class Teacher : Person { public void GetTeacher() { Console.WriteLine("我是老师"); } } public class Student : Person { public void GetStudent() { Console.WriteLine("我是学生"); } } public class Animal : Person { public void GetAnimal() { Console.WriteLine("我是野兽"); } } public class Beauty : Person { public void GetBeauty() { Console.WriteLine("我是美女"); } } }
7.里式转换
里氏转换: class Program { static void Main(string[] args) { //里氏转换:1.子类可以代替父类(给父类赋值)2.如果父类里装的是子类对象,那么我们就可以把该父类强转为子类 //Person p = new Person(); //p.SayPerson(); //Student s = new Student(); //s.SayStudent(); Person p = new Student(); p.SayPerson();//父类对象被子类赋值,只能调用到父类的方法 Person p1 = new Teacher(); p1.SayPerson(); //if (p is Teacher) //is 判断转换类型是否为该类型 //{ // Teacher s = (Teacher)p; // s.SayTeacher(); // s.SayPerson(); //} //else //{ // Console.WriteLine("转不了"); //} Student ss= p as Student; // as 强制转换为子类对象,如果不是该类型就报错 ss.SayStudent(); } } public class Person { string _name; private int _age; private char _sxe; // string _name;//private私有的只能在本类调用,如果不用private 默认私有,子类不能调用父类的私有字段,私有方法 // public string age;//共有的 // protected char sex;//受保护的,只能在继承关系里使用,用于保护父类的字段方法,只能子类和本类调用(基类和派生类) //internal 只能用于修饰类,保护程序集的,只能在当前程序集调用 //protected internal 程序集里的父子关系的调用 public string Name { get => _name; set => _name = value; } public int Age { get => _age; set => _age = value; } public char Sxe { get => _sxe; set => _sxe = value; } public void SayPerson() { Console.WriteLine("我是人类"); } } public class Student : Person { public void SayStudent() { Console.WriteLine("我是学生"); } } public class Teacher : Person { public void SayTeacher() { Console.WriteLine("我是老师"); } }