---恢复内容开始---
面向对象
(类是不占内存,实例占内存)
C#与python不用可以直接从另一个文件直接实例化一个类,不需要导包:
1、属性 字段 方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 面向对象 { class Program { static void Main(string[] args) { Person suQuan = new Person();//实例化Person类 suQuan.Name = "张三"; suQuan.Age = -21; suQuan.Gender = '春'; suQuan.CHLSS(); Console.ReadKey(); } } public class Person //定义类 { private string _name;//私有字段外部无法访问 public string Name//定义属性,使外部能够访问 { set { _name = value; } get { return _name; } } private int _age;//私有字段外部无法访问 public int Age { set { if (value < 0 || value > 100)//限制存入年龄为0-100 { value = 0; } _age = value; } get { return _age; } } private char _gender;//私有字段外部无法访问 public char Gender { set { _gender = value; } get { if (_gender != '男' && _gender != '女')//限制读取的性别只为男女 { return _gender = '男'; } return _gender; } } public void CHLSS() { Console.WriteLine("我叫{0},我今年{1}岁,我是{2}生", this.Name, this.Age, this.Gender); } } }
2、静态(static)和非静态
1)、在非静态类中可以有静态方法也可以由非静态方法。
2)、在调用实例成员时,需要使用对象名.实例成员。
3)、在调用静态成员时,需要使用类名.静态成员。
总结:静态成员都是类名去调用,实力成员使用对象调用。
静态函数中只能访问静态成员,无法访问实例成员。
实例函数中既能访问静态成员也能访问实例成员
静态类中只能使用静态成员,静态类无法实例化(静态成员只能类名调用,实例就毫无意义了)
3、构造函数
1)、构造函数没有返回值
2)、构造函数名称必须和类名一样
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 面向对象 { class Program { static void Main(string[] args) { Person suQuan = new Person("张三",-21);//实例化Person类 suQuan.CHLSS(); Console.ReadKey(); } } public class Person { public Person(string name, int age, char gender = '男') { this.Name = name; this.Age = age; this.Gender = gender; Console.WriteLine("创建对象的时候执行构造函数"); } private string _name;//私有字段外部无法访问 public string Name { set { _name = value; } get { return _name; } } private int _age;//私有字段外部无法访问 public int Age { set { if (value < 0 || value > 100) { value = 0; } _age = value; } get { return _age; } } private char _gender;//私有字段外部无法访问 public char Gender { set { _gender = value; } get { if (_gender != '男' && _gender != '女') { return _gender = '男'; } return _gender; } } public void CHLSS() { Console.WriteLine("我叫{0},我今年{1}岁,我是{2}生", this.Name, this.Age, this.Gender); } } }
4、关键字this使用
5、命名空间(namespace)
用于解决类重名问题,可以看作“类的文件夹。如果当前项目没有这个类的命名空间需要手动导入名空间:alt+shift+F10
在一个项目中应用另一个项目中的类(1)、添加引用(2)、引用命名空间
6、继承
子类从父类继承了属性和方法,但子类不继承父类的私有字段和构造函数 ,但是子类会默认的调用父类无参数的构造函数
单根性:一个类只能继承一个类;类具有传递性
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 面向对象 { class Program { static void Main(string[] args) { Person suQuan = new Teacher("张三", 21, '男', 1254);//实例化Person类 suQuan.CHLSS(); Console.ReadKey(); } } public class Person { public Person(string name, int age, char gender = '男')//构造函数 { this.Name = name; this.Age = age; this.Gender = gender; Console.WriteLine("创建对象的时候执行构造函数"); } public Person(string name, int age) : this(name, age, '男')//重载一个构造函数 { //this.Name = name; //this.Age = age; //this.Gender = gender; //Console.WriteLine("创建对象的时候执行构造函数"); } private string _name;//私有字段外部无法访问 public string Name { set { _name = value; } get { return _name; } } private int _age;//私有字段外部无法访问 public int Age { set { if (value < 0 || value > 100) { value = 0; } _age = value; } get { return _age; } } private char _gender;//私有字段外部无法访问 public char Gender { set { _gender = value; } get { if (_gender != '男' && _gender != '女') { return _gender = '男'; } return _gender; } } public void CHLSS() { Console.WriteLine("我叫{0},我今年{1}岁,我是{2}生", this.Name, this.Age, this.Gender); } } public class Teacher : Person//继承父类 { public Teacher(string name, int age, char gender, int id)//重新构造函数 : base(name, age, gender) { this.Id = id; } private int _id; public int Id { set; get; } } }
7、new 关键字
1)、创建对象 2)、隐藏从父类继承过来名字相同的成员
8、里氏转换语法
1)、子类可以赋值给父类:如果有一个地方需要一个父类做为参数,我们可以给一个子类代替
2)、 如果父类中装的是子类对象,那么可以将这个父类转为子类对象
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 里氏转换 { class Program { static void Main(string[] args) { //子类可以赋值给父类:如果有一个地方需要一个父类做为参数,我们可以给一个子类代替 Student st = new Student(); Person p =new Student(); //string s= string.Join("|", new string[] {"1","2","3"}); // 如果父类中装的是子类对象,那么可以将这个父类转为子类对象 //Student ss = (Student)p; //ss.StudentSayHello(); //is:类型转换,如果转换成功,返回true,否则false if (p is Teacher) { Teacher ss = (Teacher)p; ss.TeachertSayHello(); } else { Console.WriteLine("转换失败"); } //as:类型转换,如果转换成功返回对应的对象,否则返回null Student t = p as Student; t.StudentSayHello(); Console.ReadKey(); } } public class Person { public void PersonSayHello() { Console.WriteLine("我是父类"); } } public class Student:Person { public void StudentSayHello() { Console.WriteLine("我是学生"); } } public class Teacher : Person { public void TeachertSayHello() { Console.WriteLine("我是老师"); } } }
9、C#中的修饰符
public 公开的公共的
private 私有的只有当前类内部能够访问
protected 修饰符,只有该类和子类能访问
internal 只能在当前项目中访问
protected internal
10、集合方法
using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace 集合 { class Program { static void Main(string[] args) { //创建一个集合对象:很多数据的一个集合 ArrayList list = new ArrayList(); //长度可以任意改变 类型随意 list.Clear();//清空 list.Add(1); list.Add(3.14); list.Add("张三"); //list.Remove("张三");//删除单个元素 int[] nums = {1,2,3,4,5,6,7}; list.AddRange(nums);//添加数组 Person p = new Person(); list.Add(p); list.RemoveRange(0, 3);//索引删除 //list.Sort();//排序,需要全部相同 list.Reverse();//反转 list.Insert(1, "插入的");//索引位置插入 list.InsertRange(1,nums);//指定位置插入数组 bool b = list.Contains(1);//判断有无 for (int i = 0; i < list.Count; i++) { if (list[i] is Person) { ((Person)list[i]).SayHello();//将object类强转person } //else if (list[i] is int[]) //{ // for (int j = 0; j < ((int[])list[i]).Length; j++) // { // Console.WriteLine(((int[])list[i])[j]); // } //} else { Console.WriteLine(list[i]); } } Console.ReadKey(); } } public class Person { public void SayHello() { Console.WriteLine("我是人类"); } } }
11、Hastable键值对集合
1)var: 根据值推断出类型,但是声名是必须赋值;(类似python字典)
2)键是唯一的,使用add无法重复添加相同建,“=”添件直接覆盖建已存在的值
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Diagnostics; namespace hashtable集合 { class Program { static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add(1, "张三"); ht.Add(2, true); ht.Add(3, '男'); ht.Add(false,"错误的"); ht[1] = "新来的";//覆盖“张三” if (!ht.ContainsKey(false)) { ht[false] = "哈哈"; } else { Console.WriteLine("已经存在该键"); } Console.WriteLine(ht[false]); foreach (var item in ht.Keys)//遍历键 { Console.WriteLine(ht[item]); } Console.ReadKey(); } } }
namespace path { class Program { static void Main(string[] args) { //创建泛型集合,使用方法和集合一样 List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 }); list.AddRange(list); //集合转数组 int[] nums = list.ToArray(); List<string> listStr = new List<string>(); string[] str = listStr.ToArray(); foreach (int item in list) { Console.WriteLine(item); } Console.ReadKey(); } } }
12、path类、file类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace path { class Program { static void Main(string[] args) { string str = @"C:300dsddssffdfdsa.txt"; //获取文件名 Console.WriteLine( Path.GetFileName(str) ); //获取文件名但不包括扩展名 Console.WriteLine( Path.GetFileNameWithoutExtension(str) ); //获得文件扩展名 Console.WriteLine( Path.GetExtension(str) ); //获得文件所在文件夹名称 Console.WriteLine( Path.GetDirectoryName(str) ); //获得文件夹所在全路径 Console.WriteLine( Path.GetFullPath(str) ); //连接两个字符串作为路径 Console.WriteLine( Path.Combine(@"c:a","n.txt") ); Console.ReadKey(); } } }
namespace path { class Program { static void Main(string[] args) { string str = @"C:UsersAdministratorDesktoppj"; //创建一个文件 //File.Create(Path.Combine(str, "n.txt")); //删除一个文件 //File.Delete(Path.Combine(str, "n.txt")); //复制一个文件 //File.Copy(Path.Combine(str, "run.py"), (Path.Combine(str, "run1.py"))); //以行方式读文件 //string[] contents = File.ReadAllLines(Path.Combine(str, "run1.py")); //foreach (string item in contents) //{ // Console.WriteLine(item); //} //以字符创方式读文件 //string content = File.ReadAllText(Path.Combine(str, "run1.py")); //Console.WriteLine(content); //覆盖以行形势写入 File.WriteAllLines(Path.Combine(str, "n.txt"), new string[] { "dsda", "fdssd" }); //覆盖以字符创形势写入 File.WriteAllText(Path.Combine(str, "n.txt"),"第一次写入"); //不覆盖写入 File.AppendAllText(Path.Combine(str, "n.txt"), "有没有覆盖"); Console.ReadKey(); } } }
namespace Fil { class Program { static void Main(string[] args) { //三个参数:操作路劲 针对文件做什么操作 对文件数据数据什么操作 FileStream fsread = new FileStream(@"C:UsersAdministratorDesktoppj .txt", FileMode.OpenOrCreate, FileAccess.Read); byte[] buffer = new byte[1024 * 1024 * 5]; //3.8M 读5M //返回本次实际读取到的有效字节数 int r = fsread.Read(buffer, 0, buffer.Length); //将字节数组中没一个元素按照指定的编码格式解码成字符创 string s = Encoding.UTF8.GetString(buffer, 0, r); //关闭流 fsread.Close(); //释放流所占用的资源 fsread.Dispose(); Console.WriteLine(s); //将创建文件流对象的过程卸载Using当中,会自动帮我们释放流占用的资源 //using (FileStream fswrite = new FileStream(@"C:UsersAdministratorDesktoppj .txt", FileMode.OpenOrCreate, FileAccess.Write)) //{ // string str = "看我有没有把你覆盖"; // byte[] buffer = Encoding.UTF8.GetBytes(str); // fswrite.Write(buffer, 0, buffer.Length); //} Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace streamRead { class Program { static void Main(string[] args) { //使用streamread读文本 using (StreamReader sr = new StreamReader(@"C:UsersAdministratorDesktoppj .txt",Encoding.UTF8)) { while (!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } } //使用streamwriter读文本 using (StreamWriter sw = new StreamWriter(@"C:UsersAdministratorDesktoppj .txt",true))//ture不覆盖 { sw.Write("今天天气好晴朗"); } Console.ReadKey(); } } }
namespace 接口 { class Program { static void Main(string[] args) { //创建一个文件夹 Directory.CreateDirectory(@"c:a"); //删除文件夹 Directory.Delete(@"c:a",true); Console.WriteLine("ok"); //剪切 //Directory.Move(@"c:da", @"c:da1da"); //获得指定文件夹下所有文件全路径 //string[] path = Directory.GetFiles(@"C:UsersAdministratorDocuments", "*.jpg");//筛选jpg后缀文件 //for (int i = 0; i < path.Length; i++) //{ // Console.WriteLine(path[i]); //} //获取所有文件夹全部路径 //string[] path = Directory.GetDirectories(@"C:UsersAdministratorDocuments"); //for (int i = 0; i < path.Length; i++) //{ // Console.WriteLine(path[i]); //} //判断有无文件夹 //if (Directory.Exists(@"c:da1da")) //{ // for (int i = 0; i < 100; i++) // { // Directory.CreateDirectory(@"c:da1da" + i); // } //} Console.ReadKey(); } } }
13、装箱、拆箱
装箱:将值类型转引用类型 拆箱:将引用类型转值类型
看两种类型是否发生装箱或者拆箱,要看这两种类型是否存在继承关系
namespace path { class Program { static void Main(string[] args) { ArrayList list1 = new ArrayList(); List<int> list2 = new List<int>(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { //list1.Add(i);//装箱1000000次 list1.Add(i);//没有装箱 } sw.Stop(); Console.WriteLine(sw.Elapsed); //下面没有发生拆箱 string str = "123"; int num = Convert.ToInt32(str); // int n = 10; ICloneable x = n;//装箱 Console.ReadKey(); } } }
14、字典(原来也有字典)
namespace 字典 { class Program { static void Main(string[] args) { Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "张三"); dic.Add(2, "李四"); dic.Add(3, "王五"); dic[1] = "新来的"; foreach (KeyValuePair<int,string> kv in dic) { Console.WriteLine("{0}_{1}", kv.Key, kv.Value); } Console.ReadKey(); } } }
15、多态:虚方法,抽象类,接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 多态 { class Program { static void Main(string[] args) { //概念:让一个对象能够表现多种状态 // 虚方法 :将父类方法标记虚方法(virtual) Chinese cn1 = new Chinese("张三"); Chinese cn2 = new Chinese("李四"); Korea k1 = new Korea("金秀贤"); Korea k2 = new Korea("金贤秀"); Person[] pers = {cn1,cn2, k1, k2 }; for (int i = 0; i < pers.Length; i++) { //如果没有使用虚方法,下面代码只能打印父类的方法 pers[i].SayHello();//不再需要强转为派生类对象就可以实现派生类的方法 } Console.ReadKey(); } } public class Person { public string _name; public string Name { get; set; } public Person(string name) { this.Name = name; } public virtual void SayHello() { Console.WriteLine("我是人类,我叫{0}",this.Name); } } public class Chinese : Person { public Chinese(string name) : base(name) { this.Name = name; } public override void SayHello() { Console.WriteLine("我是中国人,我叫{0}", this.Name); } } public class Korea : Person { public Korea(string name) : base(name) { this.Name = name; } public override void SayHello() { Console.WriteLine("我是韩国人,我叫{0}", this.Name); } } }
当父类中的方法不知道如何去使用时时可以把父类写成抽象类,方法写成抽象函数
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 抽象类 { class Program { static void Main(string[] args) { Animal a = new Cat(); a.Bark(); Console.ReadKey(); } } //父类 public abstract class Animal { public abstract void Bark();//抽象方法没有方法体(无大括号) public abstract string Name { get; set; }//抽象属性 public abstract string TestString(string name); public virtual void TestVirtual() { Console.WriteLine("我是虚方法"); } } public class Dog : Animal { public override void Bark() { Console.WriteLine("狗旺旺叫"); } public override string Name { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override string TestString(string name) { throw new NotImplementedException(); } } public class Cat : Animal { public override void Bark() { Console.WriteLine("猫喵喵叫"); } public override string Name { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override string TestString(string name) { throw new NotImplementedException(); } } }
接口(interface):一种规范,实现接口的子类必须实现接口的全部成员;接口只能继承接口,
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 接口 { class Program { static void Main(string[] args) { Person person = new Person(); person.Fly(); Console.ReadKey(); } } public interface IFlyable { //接口成员不允许添加修饰符 void Fly(); //不允许写具体方法体 //string Test(); //自动属性 //string Name { get; set; } } public class Person : IFlyable { public void Fly() { Console.WriteLine("人类在飞"); } } public class Bird : IFlyable { public void Fly() { Console.WriteLine("鸟类在飞"); } } //即继承接口有继承类 语法上先写类 public class Student : Person, IFlyable { } }
16、设计模式
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 工厂设计 { class Program { static void Main(string[] args) { string brand = Console.ReadLine(); NoteBook nb = GetNoteBook(brand); nb.SayHello(); Console.ReadKey(); } public static NoteBook GetNoteBook(string brand) { NoteBook nb = null; switch (brand) { case "Lenovo": nb = new Lenovo(); break; case "IBM": nb = new IBM(); break; case "Acer": nb = new Acer(); break; case "Dell": nb = new DELL(); break; } return nb; } } public abstract class NoteBook { public abstract void SayHello(); } public class Acer: NoteBook { public override void SayHello() { Console.WriteLine("我是红星笔记本"); } } public class IBM : NoteBook { public override void SayHello() { Console.WriteLine("我是戴尔笔记本"); } } public class DELL : NoteBook { public override void SayHello() { Console.WriteLine("我是Dell笔记本"); } } public class Lenovo : NoteBook { public override void SayHello() { Console.WriteLine("我是联想笔记本"); } } }
17、进程
namespace 进程1 { class Program { static void Main(string[] args) { //Process[] pros = Process.GetProcesses(); ////查看所有进程 //foreach (var item in pros) //{ // //杀死进程 // //item.kill(); // Console.WriteLine(item); //} //通过进程打开一些应用程序 //Process.Start("calc"); //Process.Start("notepad"); //Process.Start("iexplire", "http://www.baidu.con"); //打开指定文件 ProcessStartInfo psi = new ProcessStartInfo(@"c:Jamaica.txt"); Process p = new Process(); p.StartInfo = psi; p.Start(); Console.ReadKey(); } } }
18、多线程
a、前台线程:只有多有前台线程都关闭才能完成程序关闭
b、后台线程:只有所有的前台线程结束,后台线程自动结束。
using System.Windows.Forms; using System.Threading; namespace 多线程1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Thread th; private void button1_Click(object sender, EventArgs e) { th = new Thread(Test); //将线程设置为后台线程 th.IsBackground = true; th.Start(); } private void Test() { for (int i = 0; i < 9999; i++) { Console.WriteLine(i); textBox1.Text = i.ToString(); } } private void Form1_Load(object sender, EventArgs e) { //取消跨线程访问 Control.CheckForIllegalCrossThreadCalls = false; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //当你点×的时候,判断新线程是否为null if (th!=null) { th.Abort(); } } } }