Table of Contents
10. When creating an object, you need to consider whether to implement a comparator
11. Treat == and Equals differently
12. When rewriting Equals, you must also rewrite GetHashCode
13. For type output Format string
14. Correctly implement shallow copy and deep copy
15. Use dynamic to simplify reflection implementation
Home Backend Development C#.Net Tutorial C# learning record: Writing high-quality code and improving organization suggestions 9-15

C# learning record: Writing high-quality code and improving organization suggestions 9-15

Aug 06, 2018 pm 02:57 PM
c#

9. Get used to overloading operators

When building your own types, you should always consider whether you can use operator overloading

10. When creating an object, you need to consider whether to implement a comparator

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);
    }
}
Copy after login

C# learning record: Writing high-quality code and improving organization suggestions 9-15

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);
    }
}
Copy after login

It calls the Compare method of Program

11. Treat == and Equals differently

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

12. When rewriting Equals, you must also rewrite GetHashCode

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();
}
Copy after login

When rewriting the Equals method, there should also be a type-safe interface IEquatable in advance, so the final version of rewriting Equals should be

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();
    }

}
Copy after login

13. For type output Format string

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";
    }
}
Copy after login
static void Main(string[] args)
{
    Person p1 = new Person();
    Console.WriteLine(p1);
    Console.WriteLine(p1.ToString("Chinese",null));
    Console.WriteLine(p1.ToString("English", null));
}
Copy after login

C# learning record: Writing high-quality code and improving organization suggestions 9-15

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

14. Correctly implement shallow copy and deep copy

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;
    }
}
Copy after login

Shallow copy:

C# learning record: Writing high-quality code and improving organization suggestions 9-15

Output p1.child.name is the changed child.name

deep copy of p2:

C# learning record: Writing high-quality code and improving organization suggestions 9-15

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

15. Use dynamic to simplify reflection implementation

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);
}
Copy after login

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

C# learning record: Writing high-quality code and improving organization suggestions 9-15The difference is almost 10 times

But if the number of reflections is smaller, the efficiency will be higher

C# learning record: Writing high-quality code and improving organization suggestions 9-15This 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles