c#object类中方法的使用

C#中的Object类是所有类的基类,它定义了一些通用的方法和属性,可以在任何对象上使用。以下是Object类中常用的方法和属性的使用
1.ToString():将对象转换为字符串表示形式。

string str = obj.ToString();

2.Equals():判断两个对象是否相等。

bool isEqual = obj1.Equals(obj2);

3.GetHashCode():获取对象的哈希码。

int hashCode = obj.GetHashCode();

4.GetType():获取对象的类型。

Type type = obj.GetType();

5.MemberwiseClone():创建当前对象的浅表副本

object clone = obj.MemberwiseClone();

6.ReferenceEquals():判断两个对象的引用是否相等。

bool isSameReference = object.ReferenceEquals(obj1, obj2);

以下是一个示例代码,演示了如何使用Object类的方法和属性:

class MyClass
{
    
    
   //重写父类object的tostring()方法,默认输出(namespce+classname)
    public override string ToString()
    {
    
    
        return "This is MyClass";
    }
    //重写父类equals方法,默认和==功能一样,值类型比较值是否相等,引用类型比较引用地址是否相同,string 比较字符串内容是否相同。
    public override bool Equals(object obj)
    {
    
    
        if (obj == null || GetType() != obj.GetType())
        {
    
    
            return false;
        }

        MyClass other = (MyClass)obj;
        // 判断两个对象的特定属性是否相等
        return this.Property == other.Property;
    }

    public override int GetHashCode()
    {
    
    
        return this.Property.GetHashCode();
    }

    public string Property {
    
     get; set; }
}

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        MyClass obj1 = new MyClass {
    
     Property = "Value1" };
        MyClass obj2 = new MyClass {
    
     Property = "Value2" };

        // 调用ToString()方法
        Console.WriteLine(obj1.ToString());

        // 调用Equals()方法
        bool isEqual = obj1.Equals(obj2);
        Console.WriteLine(isEqual);

        // 调用GetHashCode()方法
        int hashCode = obj1.GetHashCode();
        Console.WriteLine(hashCode);

        // 调用GetType()方法
        Type type = obj1.GetType();
        Console.WriteLine(type.Name);

        // 调用MemberwiseClone()方法
        MyClass clone = (MyClass)obj1.MemberwiseClone();
        Console.WriteLine(clone.Property);

        // 调用ReferenceEquals()方法
        bool isSameReference = object.ReferenceEquals(obj1, obj2);
        Console.WriteLine(isSameReference);
    }
}

注意:Object类中的Equals()方法判断两个对象是否相等,默认使用的是引用相等比较。如果需要自定义相等性的判断逻辑,可以在类中重写Equals()方法。同时,还可以重写==和!=运算符来实现相等性比较

猜你喜欢

转载自blog.csdn.net/qq_41942413/article/details/132613846