笔记03-.NET高级技术
第一章:各种知识点(新版)
3.索引器
索引器允许数字索引,和字符串,可以多个参数,索引器本质是方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { Person p1 = new Person(); p1[3, 5] = "hello";//set,输出x=3,y=5 string s = p1[1, 2];//get Console.WriteLine(s);//输出12 Dog d = new Dog(); d["hello"]=9;//输出s的值是hello Console.WriteLine(d["hello"]);// 输出888 int i = d["yyyy"]; Console.WriteLine(i);// 输出888 Console.ReadKey(); } class Person { public string this[int x, int y] { get { return "" + x + y; } set { Console.WriteLine("x=" + x + ",y=" + y); } } } class Dog { public int this[string s] { get { return 888; } set { Console.WriteLine("s的值是" + s); } } }
4.密闭类和静态类及扩展方法
sealed密封类 不能被继承
static静态类类 不能new,不能被继承,只能声明static成员
c#3.0特性:扩展方法
//扩展方法所在的类必须是static类
//扩展方法的第一个参数类型是被扩展的类型,类型前面标注this
//使用扩展方法的代码必须添加对扩展方法所在类的namespace的using
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { string e = "dsa@163.com"; bool b = Dog.IsEmail(e); Console.WriteLine(b); b = Dog.IsEmail2(e); Console.WriteLine(b); //扩展方法 //扩展方法所在的类必须是static类 //扩展方法的第一个参数类型是被扩展的类型,类型前面标注this //使用扩展方法的代码必须添加对扩展方法所在类的namespace的using b = e.IsEmail2(); Console.WriteLine(b); string s1 = "abcd"; Console.WriteLine(s1.Repeat(3)); Console.ReadKey(); } } static class Dog { //扩展方法 public static bool IsEmail2(this string s) { return s.Contains("@"); } public static string Repeat(this string s, int cout) { string result = ""; for (int i = 0; i < cout; i++) { result = result + s; } return result; } public static bool IsEmail(string s) { return s.Contains("@"); } }
5.深拷贝浅拷贝
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //浅拷贝 Person p1 = new Person(); p1.name = "小a"; p1.age = 18; Person p2 = p1; p1.age = 99; Console.WriteLine(p2.age);//输出99 //深拷贝 Person p3 = new Person(); p3.name = p1.name; p3.age = p1.age; p1.age = 199; Console.WriteLine(p3.age);//输出99 Console.ReadKey(); } } class Person { public string name { get; set; } public int age { get; set; } }
6.结构体及值类型引用类型
引用类型,方法调用后,一起改变
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person p = new Person(); p.name = "555"; ss(p); Console.WriteLine(p.name);//输出666 Console.ReadKey(); } public static void ss(Person s) { s.name= "666"; } } class Person { public string name { get; set; } }
结构体,是复制拷贝一份,值类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person p1 = new Person(); p1.name = "555"; p1.age = 1; Person p2 = p1; p1.age = 666; Console.WriteLine(p2.age);//输出666 Dog d1 = new Dog(); d1.name = "555"; d1.age = 1; Dog d2 = d1; d1.age = 666; Console.WriteLine(d2.age);//输出1 Console.ReadKey(); } } class Person { public string name { get; set; } public int age { get; set; } } struct Dog { public string name { get; set; } public int age { get; set; } }
什么是引用类型:引用类型派生自System.Object
什么是值类型:值类型均隐式派生自System.ValueType(ValueType其实也是继承自Object,不过是独立独行的一个分支)
值类型:数值类型,bool,结构,枚举
引用类型:字符串,数组,类,接口
引用类型变量的赋值只复制对对象的引用:引用类型在堆内存
值类型变量赋值会拷贝一个副本:值类型在栈内存:值类型一定是sealed
7.CTS.CLS.CLR
通用类型系统 CTS,Common Type System
通用语言规范 CLS, Common Language Specification
公共语言运行时 CLR, Common Language Runtime
垃圾回收 GC, Garbage Collection
8.拆箱装箱box,unbox
拆箱装箱会发生内存变化
建议用Convert
1. 装箱在值类型向引用类型转换时发生
2. 拆箱在引用类型向值类型转换时发生
装箱操作和拆箱操作是要额外耗费cpu和内存资源的,所以在c# 2.0之后引入了泛型来减少装箱操作和拆箱操作消耗。
9.关于相等
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person p1 = new Person(); p1.name = "dadada"; p1.age = 10; Person p2 = p1; Person p3 = new Person(); p3.name = "dadada"; p3.age = 10; Console.WriteLine(object.ReferenceEquals(p1, p2));//true Console.WriteLine(object.ReferenceEquals(p1, p3));//false Console.WriteLine(p1 == p2);//true Console.WriteLine(p1 == p3);//false //object的Equals方法的默认实现是比较2个变量是否同一个对象 String s1 = "abc"; string s2 = s1; string s3 = new String(new char[] { 'a', 'b', 'c' });//new 一下就会产生一个新对象 Console.WriteLine(object.ReferenceEquals(s1, s2));//true Console.WriteLine(object.ReferenceEquals(s1, s3));//false Console.WriteLine(s1 == s2);//true Console.WriteLine(s1 == s3);//true 字符串由于override了Equals方法,内部进行内容比较,所以对于字符串来讲==就是比较内容 Console.ReadKey(); } } class Person { public string name { get; set; } public int age { get; set; } }
10.字符串缓冲池
11.ref和out
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //1.作用 //ref 方法内部修改外部变量的指向 //out 方法多个返回值 //2.变量是否传入方法前赋值 //ref必须 //out不用,赋值也没用 //3.是否必须在方法中赋值 //ref 不必须 //out 必须 Person p = new Person(); p.name = "aaa"; int i = 5; Test(p, i); Console.WriteLine(p.name);//bbb Console.WriteLine(i);//5 Console.ReadKey(); } static void Test(Person p, int i) { p.name = "bbb"; i = 666; } } class Person { public string name { get; set; } public int age { get; set; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //1.作用 //ref 方法内部修改外部变量的指向 //out 方法多个返回值 //2.变量是否传入方法前赋值 //ref必须 //out不用,赋值也没用 //3.是否必须在方法中赋值 //ref 不必须 //out 必须 Person p = new Person(); p.name = "aaa"; int i = 5; Test(ref p,ref i); Console.WriteLine(p.name);//bbb Console.WriteLine(i);//666 Console.ReadKey(); } static void Test(ref Person p,ref int i) { p = new Person(); p.name = "bbb"; i = 666; } } class Person { public string name { get; set; } public int age { get; set; } }
第二章:委托,lambda,事件(新版)
1.委托
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { MyDell m1 = new MyDell(M1); MyDell m2 = M1; m1(5); Console.WriteLine(); Console.ReadKey(); } static int M1(int a) { Console.WriteLine("M1"+a); return 4; } } delegate int MyDell(int a);
2.委托应用GetMax
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //int[] nums =new int[] {3,88,9,21 };//int[]无法直接转换为object[] //string[] nums =new string[] {"" };//不会变异出错 object[] nums = new object[] { 3, 88, 9, 21 };//装箱 //object m = GetMax(nums, CompaerInt); object m = GetMax(nums, new CompareFunc(CompaerInt)); Console.WriteLine(m); object[] nums1 = new object[] { 3.14f, 55.6f, 3.5f, 8.8f };//装箱 object m2 = GetMax(nums1, new CompareFunc(CompaerFloat)); Console.WriteLine(m2); Console.ReadKey(); } //我想实现的功能,如果obj1比obj2大,则返回true,否则返回false delegate bool CompareFunc(object obj1, object obj2); static bool CompaerInt(object obj1, object obj2) { int i1 = (int)obj1; int i2 = (int)obj2; return i1 > i2; } static bool CompaerFloat(object obj1, object obj2) { float i1 = (float)obj1; float i2 = (float)obj2; return i1 > i2; } //方法只获取最大值,具体怎么比较委托去实现 //GetMax把不变的算法固定下来 static object GetMax(object[] nums, CompareFunc func) { object max = nums[0]; for (int i = 0; i < nums.Length; i++) { if (func(nums[i], max))//调用func指向的方法,判断大小 { max = nums[i]; } } return max; } }
泛型委托
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { int[] nums = new int[] { 3, 88, 9, 21 }; int m = GetMax<int>(nums, CompaerInt); Console.WriteLine(m); Console.ReadKey(); } static bool CompaerInt(int i1, int i2) { return i1 > i2; } delegate bool CompareFunc<T>(T obj1, T obj2); static T GetMax<T>(T[] nums, CompareFunc<T> func) { T max = nums[0]; for (int i = 0; i < nums.Length; i++) { if (func(nums[i], max))//调用func指向的方法,判断大小 { max = nums[i]; } } return max; } }
3.内置泛型委托Func,Action
4匿名方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { MyDel d1 = delegate (int i1, string s1) { Console.WriteLine("我是匿名方法:"+i1+s1); return true; }; bool b1 = d1(5,"aaaa"); Console.WriteLine(b1); Console.ReadKey(); } static bool F1(int i,string str) { Console.WriteLine("i="+i+",str="+str); return false; } } delegate bool MyDel(int i, string s);
5.lambda
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { Action<int> a1 = delegate (int i) { Console.WriteLine(i); }; a1(5); //lambda 表达式格式的匿名方法的写法 Action<int> a2 = (int i) => { Console.WriteLine(i); }; a2(666); Action<int> a3 = (i) => { Console.WriteLine(i); }; //如果有一个参数,可以不写参数的小括号 Action<int> a4 = i => { Console.WriteLine(i); }; Func<string, int, bool> f1 = delegate (string s, int i) { return true; }; Func<string, int, bool> f2 = (string s, int i) => { return true; }; Func<string, int, bool> f3 = (s, i) => { return true; }; //如果委托有返回值,并且方法体只有一行代码,这一行代码还是返回值,那么就可以连方法的大括号和return都省略 Func<string, int, bool> f4 = (s, i) => true; Console.ReadKey(); }
7.lambda改造GetMax
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { int[] nums = new int[] { 3, 88, 6, 9 }; //int m = GetMax(nums, CompareInt); //1. //Func<int, int, bool> f = delegate (int i1, int i2) { return i1 > i2; }; //int m = GetMax(nums, f); //2. //int m = GetMax(nums, delegate (int i1, int i2) { return i1 > i2; }); //3. //int m = GetMax(nums, (i1, i2) => { return i1 > i2; }); //4. int m = GetMax(nums, (i1, i2) => i1 > i2); Console.WriteLine(m); Console.ReadKey(); } private static bool CompareInt(int i1, int i2) { return i1 > i2; } static T GetMax<T>(T[] objs, Func<T, T, bool> ComareFunc) { T max = objs[0]; for (int i = 0; i < objs.Length; i++) { if (ComareFunc(objs[i], max)) { max = objs[i]; } } return max; } }
8.编写自己的MyWhere
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { int[] num = new int[] { 3, 5, 9, 12, 38, 9 }; IEnumerable<int> r1 = num.MyWhere(i => i > 10); foreach (int item in r1) { Console.WriteLine(item); } Console.ReadKey(); } } static class JiHeExt { public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> data, Func<T, bool> func) { //foreach()面试题:什么样的对象可以使用foreach遍历:实现了IEnumerable接口 //List ,数组 等都实现了IEnumerable List<T> resuletList = new List<T>(); foreach (T item in data) { if (func(item))//判断遍历到的这条数据是否满足条件func { resuletList.Add(item); } } return resuletList; } }
9.集合常用高级扩展方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { List<int> list = new List<int>(); list.Add(3); list.Add(9); list.Add(8); list.Add(16); list.Add(99); IEnumerable<int> data = list.Where(i => i > 10); foreach (var item in data) { Console.WriteLine(item); } Console.ReadKey(); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { List<int> list = new List<int>(); list.Add(3); list.Add(9); list.Add(8); list.Add(16); list.Add(99); IEnumerable<int> data = list.Select(i => i * 10); foreach (var item in data) { Console.WriteLine(item); } Console.ReadKey(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { List<int> list = new List<int>(); list.Add(3); list.Add(9); list.Add(8); list.Add(16); list.Add(99); IEnumerable<string> data = list.Select(i => "批量添加"+i * 10); foreach (var item in data) { Console.WriteLine(item); } Console.ReadKey(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person[] persons = new Person[] { new Person("baidu", 8), new Person("qq", 18), new Person("sina", 5) }; int sun1 = persons.Sum(p => p.age); Console.WriteLine(sun1); Console.ReadKey(); } } class Person { public Person() { } public Person(string name, int age) { this.name = name; this.age = age; } public string name { get; set; } public int age { get; set; } }
10.委托的组合
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { delegate void MyDel(int i); static void Main(string[] args) { MyDel d1 = F1; MyDel d2 = F2; MyDel d3 = F3; MyDel d4 = d1 + d2 + d3; MyDel d5 = new MyDel(F1) + new MyDel(F2) + new MyDel(F3); d4(9); d5(1); Console.ReadKey(); } static void F1(int i) { Console.WriteLine("我是f1:" + i); } static void F2(int i) { Console.WriteLine("我是f2:" + i); } static void F3(int i) { Console.WriteLine("我是f3:" + i); } }
11.事件入门
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person p1 = new Person(); p1.OnBenMingNian += BMN;//注册一个监听 p1.OnBenMingNian += BMN2;//注册一个监听 p1.Age = 24; Console.WriteLine(p1.Age); Console.ReadKey(); } static void BMN() { Console.WriteLine("到了本命年了"); } static void BMN2() { Console.WriteLine("到了本命年了2"); } } class Person { private int age; public int Age { get { return this.age; } set { this.age = value; if (value % 12 == 0) { if (OnBenMingNian != null) { //触发事件 OnBenMingNian(); } } } } public event Action OnBenMingNian;//event 委托类型 事件的名字 //public Action OnBenMingNian; 加event 就是事件,不加event就是委托 //委托可以p1.OnBenMingNian =null //事件不可以p1.OnBenMingNian = null }
12.事件本质揭秘
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Person p1 = new Person(); p1.OnBenMingNian += BMN;//注册一个监听 p1.OnBenMingNian += BMN2;//注册一个监听 p1.Age = 24; Console.WriteLine(p1.Age); Console.ReadKey(); } static void BMN() { Console.WriteLine("到了本命年了"); } static void BMN2() { Console.WriteLine("到了本命年了2"); } } class Person { private int age; public int Age { get { return this.age; } set { this.age = value; if (value % 12 == 0) { if (this._OnBenMingNian != null) { //触发事件 this._OnBenMingNian(); } } } } //public event Action OnBenMingNian;//event 委托类型 事件的名字 //public Action OnBenMingNian; //加event 就是事件,不加event就是委托 //委托可以p1.OnBenMingNian =null //事件不可以p1.OnBenMingNian = null private Action _OnBenMingNian; public event Action OnBenMingNian { add { this._OnBenMingNian += value; } remove { this._OnBenMingNian -= value; } } }
第三章:反射和Attribute(新版)
1.反射入门及Type
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace 反射 { class Program { static void Main(string[] args) { Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); Person p4 = new Person(); //下面有N种获取Person对应的Type对象的方法 //最终都是获得的同一个对象,因为一个类就对应一个对象 Type t1 = p1.GetType(); Type t2 = p2.GetType(); Type t3 = typeof(Person); Type t4 = Type.GetType("反射.Person"); Console.WriteLine(t1); Console.WriteLine(t2); Console.WriteLine(t3); Console.WriteLine(t4); Console.WriteLine(object.ReferenceEquals(t1, t2)); Console.WriteLine(object.ReferenceEquals(t2, t3)); Console.WriteLine(object.ReferenceEquals(t3, t4)); //Activator.CreateInstance(t1)动态创建类,类必须public 且无参的构造函数 object obj = Activator.CreateInstance(t1);//动态创建t1指向的类的对象.new Person(); Console.WriteLine(obj); Console.ReadKey(); } } class Person//一个类对象一个Type对象 { public override string ToString() { return "我是Person"; } } }
2.this的本质
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //this不是代表"当前类",而是代表"当前对象",this看做当前对象的一个特殊的变量 Child1 c1 = new Child1(); c1.Hell();//this.Child1 Child2 c2 = new Child2(); c2.Hell();//this.Child2 Person p1 = new Person(); p1.Hell();//this.Person Console.ReadKey(); } } class Person { public void Hell() { Type type = this.GetType(); Console.WriteLine(type); } } class Child1 : Person { } class Child2 : Person { }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { //this不是代表"当前类",而是代表"当前对象",this看做当前对象的一个特殊的变量 Child1 c1 = new Child1(); c1.Hell();//this.Child1 Child2 c2 = new Child2(); c2.Hell();//this.Child2 Person p1 = new Person(); p1.Hell();//this.Person Console.ReadKey(); } } class Person { public void Hell() { this.Test(); } public virtual void Test() { Console.WriteLine("parent test"); } } class Child1 : Person { public override void Test() { Console.WriteLine("Child1 test"); } } class Child2 : Person { public override void Test() { Console.WriteLine("Child2 test"); } }
3.Type的常见成员
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace type常见成员 { class Program { static void Main(string[] args) { /* Type t1 = typeof(Person); Type t1Type = t1.GetType(); Console.WriteLine(t1Type); Console.WriteLine(t1.Name); Console.WriteLine(t1.FullName);//type常见成员.Person Console.WriteLine(t1Type.BaseType.BaseType.BaseType); int[] nums = new int[] { 3,5,8}; Type t2 = nums.GetType(); Console.WriteLine(t2.IsArray);*/ Type t1 = typeof(Person); //获取构造函数 ConstructorInfo c1 = t1.GetConstructor(new Type[0]); ConstructorInfo c2 = t1.GetConstructor(new Type[] { typeof(string) }); ConstructorInfo c3 = t1.GetConstructor(new Type[] { typeof(int), typeof(string) }); Console.WriteLine(c1); Console.WriteLine(c2); Console.WriteLine(c3); FieldInfo[] fields = t1.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo field in fields) { Console.WriteLine(field); } //方法 MethodInfo[] methods = t1.GetMethods(); foreach (var method in methods) { Console.WriteLine(method); } MethodInfo m1 = t1.GetMethod("SayHi", new Type[0]); Console.WriteLine(m1); PropertyInfo []peopers = t1.GetProperties(); foreach (PropertyInfo prop in peopers) { Console.WriteLine(prop); } PropertyInfo peoper = t1.GetProperty("Name"); Console.WriteLine(); Console.ReadKey(); } } class Person { public Person() { } public Person(string name) { } public Person(int i, string name) { } public string Name { get; set; } public int Age { get; set; } public void SayHi() { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } public void SayHi(string str) { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } } }
4.MethodInfo,Propert
5.反射调用示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace type常见成员 { class Program { static void Main(string[] args) { Type type = typeof(Person); object obj = Activator.CreateInstance(type);//new Person object obj2 = type.GetConstructor(new Type[0]).Invoke(new object[0]); PropertyInfo propName = type.GetProperty("Name");//获取Name属性 propName.SetValue(obj, "aaa");//相当于obj.Name="aaa"; PropertyInfo propAge = type.GetProperty("Age"); propAge.SetValue(obj, 18);//obj.Age=18; //获得SayHi()方法 MethodInfo methodSayHi = type.GetMethod("SayHi", new Type[0]); methodSayHi.Invoke(obj, new object[0]);//在obj指向的对象上调用SayHi.相当于obj.SayHi Console.ReadKey(); } } class Person { public Person() { } public Person(string name) { } public Person(int i, string name) { } public string Name { get; set; } public int Age { get; set; } public void SayHi() { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } public void SayHi(string str) { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } } }
6.模拟propertyGrid
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace 模拟 { class Program { static void Main(string[] args) { Person p1 = new Person(); p1.Age = 18; p1.Name = "aaa"; ShowObject(p1); Console.ReadKey(); } static void ShowObject(object obj) { Type type = obj.GetType(); PropertyInfo[] props = type.GetProperties(); foreach (PropertyInfo prop in props) { if (prop.CanRead) { string propName = prop.Name; object value = prop.GetValue(obj);//获取obj对象的prop属性的值 Console.WriteLine(propName + "=" + value); } } } } class Person { public Person() { } public Person(string name) { } public Person(int i, string name) { } public string Name { get; set; } public int Age { get; set; } public void SayHi() { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } public void SayHi(string str) { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } } }
7.反射案例:对象的拷贝
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace 对象浅拷贝 { class Program { static void Main(string[] args) { Person p1 = new Person(); p1.Age = 18; p1.Name = "aaa"; Person p3 = (Person)MyClone(p1); p3.SayHi(); Console.WriteLine(object.ReferenceEquals(p1, p3)); Console.ReadKey(); } //创建obj对象的一份拷贝 static object MyClone(object obj) { Type type = obj.GetType(); Object newObj = Activator.CreateInstance(type);//创建一个拷贝对象 foreach (var prop in type.GetProperties()) { if (prop.CanRead && prop.CanWrite)//get.set { object value = prop.GetValue(obj);//获取obj对象的属性的值 prop.SetValue(newObj, value);//把值赋值给newObj对应的属性 } } return newObj; } } class Person { public string Name { get; set; } public int Age { get; set; } public void SayHi() { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } } }
8.Attribute简介
EF模式就和反射有关
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PropertyGridTest01 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Person p1 = new Person(); p1.Age = 18; p1.Name = "aaa"; propertyGrid1.SelectedObject = p1; p1.SayHi(); } } class Person { public Person() { } public Person(string name) { } public Person(int i, string name) { } [ReadOnly(true)]//只读 [DisplayName("姓名")]//显示名字 public string Name { get; set; } [Browsable(false)]//不显示 [DisplayName("年龄")] public int Age { get; set; } [Obsolete]//已过时 public void SayHi() { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } public void SayHi(string str) { Console.WriteLine("大家好,我是" + this.Name + ",我的年龄是" + this.Age); } } }
第四章:正则、序列化、XML(新版)
1.正则表达式基本概念
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
.表示除了\n以外的任意的单个字符 [0-9]表示的是0到9之间任何一个整数数字;[a-z]任意一个小写字母,[A-Z]任意一个大写字母 \d数字,\D非数字,\s空白,\S非空白,\w小写字母和数字和汉字,\W特殊符号。正则表达式中的\是真的\。 \表示对于.等特殊字符转义 ()提升优先级别和提取组 []代表一个区间中的任意一个[abc\d]就代表abc或者数字中的任意一个字符 | 或者 +是出现1次到无限次 *是出现0次到无限次 ?是出现0次到1次 {5}出现5次,{1,2}一次或两次,{5,8}为5至8次,{1,}最少一次,{3,}最少3次 ^以…开始,$以…结束
2.正则表达式匹配案例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1、这样写是有缺陷的Regex.IsMatch("18911111234", @"\d{11}")、Regex.IsMatch("3333333333333333", @"\d{11}"),应该使用^$改成Regex.IsMatch("18911111234333", @"^\d{11}$") 2、手机号:@"^1\d{10}$" 3、@"^\d{5,10}$"匹配QQ号 4、ipv4地址:@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$" 正则表达式很难“一步到位”。192.168.1.15 5、@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" 匹配邮箱 6、[\u4e00-\u9fa5] 单个汉字 @"^[\u4e00-\u9fa5]{2,4}$" 长度为2-4的汉字姓名 7、身份证号(15位、18位数字):@"^(\d{15})$|^(\d{18})$" 8、身份证号(18位,最后一位可能是x) @"^(\d{17})[\dxX]$" 8、日期格式:^\d{4}\-\d{1,2}\-\d{1,2}$
3.正则表达式的内容提取
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { Console.WriteLine(Regex.IsMatch("6725d", @"^\d{4}$")); Match match = Regex.Match("2016-5-15", @"^(\d{4})\-(\d{1,2})\-(\d{1,2})$"); if (match.Success) { string year = match.Groups[1].Value;//序号从1开始 string mouth = match.Groups[2].Value; string day = match.Groups[3].Value; Console.WriteLine(year + "-" + mouth + "-" + day); } else { Console.WriteLine("不匹配"); } Console.ReadKey(); }
4.序列化的应用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace 序列化 { class Program { static void Main(string[] args) { //序列化 Person p1 = new Person(); p1.Name = "tom"; p1.Age = 18; BinaryFormatter binfor = new BinaryFormatter(); using (FileStream fs = File.OpenWrite(@"C:\Users\wyl\Desktop\1.data")) { binfor.Serialize(fs, p1);//把p1指向的对象序列化保存到fs流中 } //反序列化 BinaryFormatter binfor1 = new BinaryFormatter(); using (FileStream fs = File.OpenRead(@"C:\Users\wyl\Desktop\1.data")) { Person p2 = (Person)binfor1.Deserialize(fs); } Console.ReadKey(); } } [Serializable] class Person { public string Name { get; set; } public int Age { get; set; } } }
5.
7.XML的读取
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
XmlDocument doc = new XmlDocument(); doc.Load(@"C:\temp\a.xml"); XmlNodeList students = doc.DocumentElement.ChildNodes;//Student节点集合 foreach (XmlNode stu in students) { XmlElement element = (XmlElement)stu; string stuId = element.GetAttribute("StuID"); XmlNode nameNode = element.SelectSingleNode("StuName");//获取Person节点的Name节点 string name = nameNode.InnerText; Console.WriteLine(stuId + "," + name); }
8.XML的生成
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Person { public Person(int id, string name, int age) { this.Id = id; this.Name = name; this.Age = age; } public int Id { set; get; } public string Name { set; get; } public int Age { set; get; } } Person[] persons = { new Person(1, "rupeng", 8), new Person(2, "baidu", 6) }; XmlDocument doc = new XmlDocument(); XmlElement ePersons = doc.CreateElement("Persons"); doc.AppendChild(ePersons);//添加根节点 foreach (Person person in persons) { XmlElement ePerson = doc.CreateElement("Person"); ePerson.SetAttribute("id", person.Id.ToString()); XmlElement eName = doc.CreateElement("Name"); eName.InnerText = person.Name; XmlElement eAge = doc.CreateElement("Age"); eAge.InnerText = person.Age.ToString(); ePerson.AppendChild(eName); ePerson.AppendChild(eAge); ePersons.AppendChild(ePerson); } doc.Save("d:/temp/1.xml");
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!