Object 类

定义

支持 .NET 类层次结构中的所有类,并为派生类提供低级别服务。Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. 这是所有 .NET 类的最终基类;它是类型层次结构的根。This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.

public ref class Object
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class Object
type obj = class
Public Class Object
属性

示例

下面的示例定义派生自 Object 类的点类型,并重写 Object 类的许多虚方法。The following example defines a Point type derived from the Object class and overrides many of the virtual methods of the Object class. 此外,该示例还演示了如何调用 Object 类的许多静态和实例方法。In addition, the example shows how to call many of the static and instance methods of the Object class.

using namespace System;

// The Point class is derived from System.Object.
ref class Point
{
public:
    int x;
public:
    int y;

public:
    Point(int x, int y)
    {
        this->x = x;
        this->y = y;
    }

public:
    virtual bool Equals(Object^ obj) override
    {
        // If this and obj do not refer to the same type,
        // then they are not equal.
        if (obj->GetType() != this->GetType())
        {
            return false;
        }

        // Return true if  x and y fields match.
        Point^ other = (Point^) obj;
        return (this->x == other->x) && (this->y == other->y);
    }

    // Return the XOR of the x and y fields.
public:
    virtual int GetHashCode() override 
    {
        return x ^ y;
    }

    // Return the point's value as a string.
public:
    virtual String^ ToString() override 
    {
        return String::Format("({0}, {1})", x, y);
    }

    // Return a copy of this point object by making a simple
    // field copy.
public:
    Point^ Copy()
    {
        return (Point^) this->MemberwiseClone();
    }
};

int main()
{
    // Construct a Point object.
    Point^ p1 = gcnew Point(1, 2);

    // Make another Point object that is a copy of the first.
    Point^ p2 = p1->Copy();

    // Make another variable that references the first
    // Point object.
    Point^ p3 = p1;

    // The line below displays false because p1 and 
    // p2 refer to two different objects.
    Console::WriteLine(
        Object::ReferenceEquals(p1, p2));

    // The line below displays true because p1 and p2 refer
    // to two different objects that have the same value.
    Console::WriteLine(Object::Equals(p1, p2));

    // The line below displays true because p1 and 
    // p3 refer to one object.
    Console::WriteLine(Object::ReferenceEquals(p1, p3));

    // The line below displays: p1's value is: (1, 2)
    Console::WriteLine("p1's value is: {0}", p1->ToString());
}

// This code produces the following output.
//
// False
// True
// True
// p1's value is: (1, 2)
using System;

// The Point class is derived from System.Object.
class Point
{
    public int x, y;

    public Point(int x, int y) 
    {
        this.x = x;
        this.y = y;
    }
    
    public override bool Equals(object obj) 
    {
        // If this and obj do not refer to the same type, then they are not equal.
        if (obj.GetType() != this.GetType()) return false;

        // Return true if  x and y fields match.
        var other = (Point) obj;
        return (this.x == other.x) && (this.y == other.y);
    }

    // Return the XOR of the x and y fields.
    public override int GetHashCode() 
    {
        return x ^ y;
    }

    // Return the point's value as a string.
    public override String ToString() 
    {
        return $"({x}, {y})";
    }

    // Return a copy of this point object by making a simple field copy.
    public Point Copy() 
    {
        return (Point) this.MemberwiseClone();
    }
}

public sealed class App
{
    static void Main() 
    {
        // Construct a Point object.
        var p1 = new Point(1,2);

        // Make another Point object that is a copy of the first.
        var p2 = p1.Copy();

        // Make another variable that references the first Point object.
        var p3 = p1;

        // The line below displays false because p1 and p2 refer to two different objects.
        Console.WriteLine(Object.ReferenceEquals(p1, p2));

        // The line below displays true because p1 and p2 refer to two different objects that have the same value.
        Console.WriteLine(Object.Equals(p1, p2));
      
        // The line below displays true because p1 and p3 refer to one object.
        Console.WriteLine(Object.ReferenceEquals(p1, p3));
        
        // The line below displays: p1's value is: (1, 2)
        Console.WriteLine($"p1's value is: {p1.ToString()}");
    }
}

// This code example produces the following output:
//
// False
// True
// True
// p1's value is: (1, 2)
//
' The Point class is derived from System.Object.
Class Point
    Public x, y As Integer
    
    Public Sub New(ByVal x As Integer, ByVal y As Integer) 
        Me.x = x
        Me.y = y
    End Sub
    
    Public Overrides Function Equals(ByVal obj As Object) As Boolean 
        ' If Me and obj do not refer to the same type, then they are not equal.
        Dim objType As Type = obj.GetType()
        Dim meType  As Type = Me.GetType()
        If Not objType.Equals(meType) Then
            Return False
        End If 
        ' Return true if  x and y fields match.
        Dim other As Point = CType(obj, Point)
        Return Me.x = other.x AndAlso Me.y = other.y
    End Function 

    ' Return the XOR of the x and y fields.
    Public Overrides Function GetHashCode() As Integer 
        Return (x << 1) XOR y
    End Function 

    ' Return the point's value as a string.
    Public Overrides Function ToString() As String 
        Return $"({x}, {y})"
    End Function

    ' Return a copy of this point object by making a simple field copy.
    Public Function Copy() As Point 
        Return CType(Me.MemberwiseClone(), Point)
    End Function
End Class  

NotInheritable Public Class App
    Shared Sub Main() 
        ' Construct a Point object.
        Dim p1 As New Point(1, 2)
        
        ' Make another Point object that is a copy of the first.
        Dim p2 As Point = p1.Copy()
        
        ' Make another variable that references the first Point object.
        Dim p3 As Point = p1
        
        ' The line below displays false because p1 and p2 refer to two different objects.
        Console.WriteLine([Object].ReferenceEquals(p1, p2))

        ' The line below displays true because p1 and p2 refer to two different objects 
        ' that have the same value.
        Console.WriteLine([Object].Equals(p1, p2))

        ' The line below displays true because p1 and p3 refer to one object.
        Console.WriteLine([Object].ReferenceEquals(p1, p3))
        
        ' The line below displays: p1's value is: (1, 2)
        Console.WriteLine($"p1's value is: {p1.ToString()}")
    
    End Sub
End Class
' This example produces the following output:
'
' False
' True
' True
' p1's value is: (1, 2)
'

注解

语言通常不需要类声明从 Object 继承,因为继承是隐式的。Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit.

由于 .NET 中的所有类均派生自 Object,因此在 Object 类中定义的每个方法都可用于系统中的所有对象。Because all classes in .NET are derived from Object, every method defined in the Object class is available in all objects in the system. 派生类可以和重写其中一些方法,其中包括:Derived classes can and do override some of these methods, including:

  • Equals-支持对象之间的比较。Equals - Supports comparisons between objects.

  • Finalize-在自动回收对象之前执行清理操作。Finalize - Performs cleanup operations before an object is automatically reclaimed.

  • GetHashCode-生成与对象的值相对应的数字以支持使用哈希表。GetHashCode - Generates a number corresponding to the value of the object to support the use of a hash table.

  • ToString 制造描述类的实例的用户可读文本字符串。ToString - Manufactures a human-readable text string that describes an instance of the class.

性能注意事项Performance Considerations

如果要设计的类(如集合)必须处理任何类型的对象,则可以创建接受 Object 类的实例的类成员。If you are designing a class, such as a collection, that must handle any type of object, you can create class members that accept instances of the Object class. 但是,对类型进行装箱和取消装箱的过程会产生性能开销。However, the process of boxing and unboxing a type carries a performance cost. 如果你知道新类将经常处理某些值类型,则可以使用以下两种策略之一来最大程度地减少装箱成本。If you know your new class will frequently handle certain value types you can use one of two tactics to minimize the cost of boxing.

  • 创建接受 Object 类型的常规方法,并创建一组特定于类型的方法重载,这些重载接受你希望类经常处理的每个值类型。Create a general method that accepts an Object type, and a set of type-specific method overloads that accept each value type you expect your class to frequently handle. 如果存在接受调用参数类型的特定于类型的方法,则不会发生任何装箱并调用类型特定的方法。If a type-specific method exists that accepts the calling parameter type, no boxing occurs and the type-specific method is invoked. 如果没有与调用参数类型匹配的方法参数,则将参数装箱,并调用常规方法。If there is no method argument that matches the calling parameter type, the parameter is boxed and the general method is invoked.

  • 将类型及其成员设计为使用泛型。Design your type and its members to use generics. 当你创建类的实例并指定泛型类型参数时,公共语言运行时将创建一个封闭式泛型类型。The common language runtime creates a closed generic type when you create an instance of your class and specify a generic type argument. 泛型方法是类型特定的,可以在不装箱调用参数的情况下调用。The generic method is type-specific and can be invoked without boxing the calling parameter.

尽管有时需要开发接受和返回 Object 类型的通用类,但你可以通过提供特定于类型的类来处理常用类型,从而提高性能。Although it is sometimes necessary to develop general purpose classes that accept and return Object types, you can improve performance by also providing a type-specific class to handle a frequently used type. 例如,提供特定于设置和获取布尔值的类可消除装箱和取消装箱布尔值的成本。For example, providing a class that is specific to setting and getting Boolean values eliminates the cost of boxing and unboxing Boolean values.

构造函数

Object()

初始化 Object 类的新实例。Initializes a new instance of the Object class.

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

Equals(Object, Object)

确定指定的对象实例是否被视为相等。Determines whether the specified object instances are considered equal.

Finalize()

在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

ReferenceEquals(Object, Object)

确定指定的 Object 实例是否是相同的实例。Determines whether the specified Object instances are the same instance.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

适用于

线程安全性

此类型的公共静态(Shared Visual Basic)成员是线程安全的。Public static (Shared in Visual Basic) members of this type are thread safe. 实例成员不一定是线程安全的。Instance members are not guaranteed to be thread-safe.