📜  C#|对象类别(1)

📅  最后修改于: 2023-12-03 15:00:15.760000             🧑  作者: Mango

C# | Object Class

Introduction

In C#, Object is the base class for all types. Every class in C# directly or indirectly derives from Object. This means that Object provides basic functionalities and properties to all classes and objects in C#. Understanding the Object class is important for every C# programmer.

The Object class provides several methods such as ToString(), Equals(), and GetHashCode(). These methods are commonly used in C# programming and are available to all objects and classes.

Methods
ToString()

The ToString() method returns a string that represents the current object. By default, ToString() returns the fully qualified name of the class. However, it's common for classes to override this method to provide a custom implementation that returns a more meaningful representation of the object.

public override string ToString()
{
    return $"Person[{Name}, {Age}]";
}
Equals()

The Equals() method determines whether the current object is equal to another object. By default, Equals() compares objects by reference equality, which means it returns true only if the objects refer to the same memory location. However, it's common for classes to override Equals() to provide custom comparison logic.

public override bool Equals(object obj)
{
    if (obj == null || GetType() != obj.GetType())
    {
        return false;
    }
    
    // Custom comparison logic here
}
GetHashCode()

The GetHashCode() method returns a hash code for the current object. This method is used by hash tables to quickly lookup objects. By default, GetHashCode() returns the object's memory address as a hash code. However, it's common for classes to override GetHashCode() to provide custom hash code generation.

public override int GetHashCode()
{
    unchecked
    {
        int hash = 17;
        hash = hash * 23 + Name.GetHashCode();
        hash = hash * 23 + Age.GetHashCode();
        return hash;
    }
}
Conclusion

The Object class is the base class for all types in C#. It provides several methods such as ToString(), Equals(), and GetHashCode() that are commonly used in C# programming. Understanding the Object class is important for every C# programmer.