Home >Backend Development >C#.Net Tutorial >C# learning record: Writing high-quality code and improving organization suggestions 9-15
9. Get used to overloading operators
When building your own types, you should always consider whether you can use operator overloading
If you need to sort, there are two comparator implementations
class FirstType : IComparable<FirstType> { public string name; public int age; public FirstType(int age) { name = "aa"; this.age = age; } public int CompareTo(FirstType other) { return other.age.CompareTo(age); } } static void Main(string[] args) { FirstType f1 = new FirstType(3); FirstType f2 = new FirstType(5); FirstType f3 = new FirstType(2); FirstType f4 = new FirstType(1); List<FirstType> list = new List<FirstType> { f1,f2,f3,f4 }; list.Sort(); foreach (var item in list) { Console.WriteLine(item); } }
or the second one
class Program : IComparer<FirstType> { static void Main(string[] args) { FirstType f1 = new FirstType(3); FirstType f2 = new FirstType(5); FirstType f3 = new FirstType(2); FirstType f4 = new FirstType(1); List<FirstType> list = new List<FirstType> { f1,f2,f3,f4 }; list.Sort(new Program()); foreach (var item in list) { Console.WriteLine(item); } } int IComparer<FirstType>.Compare(FirstType x, FirstType y) { return x.age.CompareTo(y.age); } }
It calls the Compare method of Program
Whether it is == or Equals:
For value types , if the values of the types are equal, it returns True
For reference types, if the types point to the same object, it returns True
and they can all be overloaded
For As a special reference class like string, Microsoft may think that its practical significance is more inclined to a value type, so in FCL (Framework Class Library) String comparison is overloaded as value comparison, not for the reference itself
In terms of design, many reference types will be similar to string types, such as people with the same ID number. Then we think it is a person. At this time, we need to overload the Equals method.
Generally speaking, for reference types, we need to define the characteristics of equal values. We should only override the Equals method and let == Indicates reference equality, so we can compare whichever one we want
Since both operators "==" and "Equals" can be overloaded as "value equality" and "reference equality", for the sake of clarity, FCL provides object.ReferenceEquals(); to compare whether two instances are the same reference
Used when judging ContainsKey in the dictionary It is a HashCode of key type, so if we want to use a certain value in the type as the judgment condition, we need to re-GetHashCode. Of course, there are other methods that use HashCode to judge whether they are equal. If we do not rewrite, other problems may occur. The effect
public override int GetHashCode() { //这样写是为了减少HashCode重复的概率,至于为什么这样写我也不清楚。。 记着就行 return (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "#" + age).GetHashCode(); }
When rewriting the Equals method, there should also be a type-safe interface IEquatable
class FirstType : IEquatable<FirstType> { public string name; public int age; public FirstType(int age) { name = "aa"; this.age = age; } public override bool Equals(object obj) { return age.Equals(((FirstType)obj).age); } public bool Equals(FirstType other) { return age.Equals(other.age); } public override int GetHashCode() { return (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "#" + age).GetHashCode(); } }
class Person : IFormattable { public override string ToString() { return "Default Hello"; } public string ToString(string format, IFormatProvider formatProvider) { switch (format) { case "Chinese": return "你好"; case "English": return "Hello"; } return "helo"; } }
static void Main(string[] args) { Person p1 = new Person(); Console.WriteLine(p1); Console.WriteLine(p1.ToString("Chinese",null)); Console.WriteLine(p1.ToString("English", null)); }
After inheriting the IFormattable interface, you can pass parameters in ToString to call different ToStrings, and the above default ToString will not be called
There is also an IFormatProvider interface, I haven’t studied it yet
Whether it is a deep copy or a deep copy Shallow copy, Microsoft has seen that the type inherits the ICloneable interface to clearly tell the caller: this type can be copied
//记得在类前添加[Serializable]的标志 [Serializable] class Person : ICloneable { public string name; public Child child; public object Clone() { //浅拷贝 return this.MemberwiseClone(); } /// <summary> /// 深拷贝 /// 我也不清楚为什么这样写 /// </summary> /// <returns></returns> public Person DeepClone() { using (Stream objectStream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(objectStream, this); objectStream.Seek(0, SeekOrigin.Begin); return formatter.Deserialize(objectStream) as Person; } } } [Serializable] class Child { public string name; public Child(string name) { this.name = name; } public override string ToString() { return name; } }
Shallow copy:
Output p1.child.name is the changed child.name
deep copy of p2:
The output is the original
Deep copy is for reference types. In theory, the string type is a reference type. However, due to the special nature of the reference type, Object.MemberwiseClone still creates a copy of it. That is to say, during the shallow copy process, we should copy the string Treat it as a value type
static void Main(string[] args) { //使用反射 Stopwatch watch = Stopwatch.StartNew(); Person p1 = new Person(); var add = typeof(Person).GetMethod("Add"); for (int i = 0; i < 1000000; i++) { add.Invoke(p1, new object[] { 1, 2 }); } Console.WriteLine(watch.ElapsedTicks); //使用dynamic watch.Reset(); watch.Start(); dynamic d1 = new Person(); for (int i = 0; i < 1000000; i++) { d1.Add(1, 2); } Console.WriteLine(watch.ElapsedTicks); }
It can be seen that using dynamic will be more beautiful and concise than the code written using reflection, and the efficiency of multiple runs is also It will be higher, because dynamic will be cached after running for the first time
The difference is almost 10 times
But if the number of reflections is smaller, the efficiency will be higher
This is the result of running 100 times
But in many cases efficiency is not necessary. It is always recommended to use dynamic to simplify the implementation of reflection
Related articles:
C# Learning Record: Writing High-quality Code Improvement and Organizing Suggestions 1-3
C# Learning Record: Writing High-Quality Code Improvement and Organizing Suggestions 4-8
The above is the detailed content of C# learning record: Writing high-quality code and improving organization suggestions 9-15. For more information, please follow other related articles on the PHP Chinese website!