code
1using System; 2using System.Collections.Generic; 3using System.Text; 4 5using Microsoft.VisualStudio.TestTools.UnitTesting; 6 7namespace Identity 8{ 9 class Program10 {11 static void Main(string[] args)12 {13 MyClass my1 = new MyClass(1);14 MyClass my2 = new MyClass(1);15 Assert.IsFalse(my1.Equals(my2));//引用类型:没有指向同一内存地址1617 int i1 = 1;18 int i2 = 1;19 Assert.IsTrue(i1.Equals(i2));//值类型:通过反射2021 MyStruct myStruct1 = new MyStruct(1,"1");22 MyStruct myStruct2 = new MyStruct(1,"1");23 Assert.IsTrue(myStruct1.Equals(myStruct2));//值类型:通过反射,比每个属性值。2425 string s1 = "1";26 string s2 = "1";27 Assert.IsTrue(s1.Equals(s2));//String为引用类型,但其Equal方法并重写,行为与值类型一样。2829 MyCopStruct mc1 = new MyCopStruct(new MyClass(1));30 MyCopStruct mc2 = new MyCopStruct(new MyClass(1));31 Assert.IsFalse(mc1.Equals(mc2));//值类型:通过反射,比每个属性值。属性为引用类型,是不同实例。3233 MyCopStruct mc11 = new MyCopStruct(my1);34 MyCopStruct mc12 = new MyCopStruct(my1);35 Assert.IsTrue(mc11.Equals(mc12));/**/////值类型:通过反射,比每个属性值。属性为引用类型,是相同实例。3637 MyCopStruct1 mc111 = new MyCopStruct1(mc11);38 MyCopStruct1 mc112 = new MyCopStruct1(mc12);39 Assert.IsTrue(mc111.Equals(mc112));/**/////值类型:通过反射,比每个属性值。属性为值类型,且值相同。4041 Console.WriteLine("OK");42 Console.ReadKey();43 }44 }4546 public class MyClass47 {48 public int name;4950 public MyClass(int name)51 {52 this.name = name;53 }54 }5556 public struct MyStruct57 {58 public int name;59 public string strName;6061 public MyStruct(int name,string strName)62 {63 this.name = name;64 this.strName = strName;65 }66 }6768 public struct MyCopStruct69 {70 public MyClass myclass;7172 public MyCopStruct(MyClass myclass)73 {74 this.myclass = myclass;75 }76 }7778 public struct MyCopStruct179 {80 public MyCopStruct myclass;8182 public MyCopStruct1(MyCopStruct myclass)83 {84 this.myclass = myclass;85 }86 }8788 public class MyClass289 {90 public override bool Equals(object obj)//需要同时重写GetHashCode,不知道为啥。91 {92 return base.Equals(obj);93 }94 public override int GetHashCode()95 {96 return base.GetHashCode();97 }98 }99}
转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/05/17/750392.html
转载请注明原文地址: https://win8.8miu.com/read-1482928.html