search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: basic knowledge (12) super class Object

The three major characteristics of object-oriented: encapsulation, inheritance, and polymorphism. So where do classes inherit from? In object-oriented languages, there is the concept of base class or super class, that is, all classes inherit from this class. This super class is called Object. The Object class is described in .net like this:
Supports all classes in the .NET Framework class hierarchy and provides low-level services for derived classes. This is the ultimate base class for all classes in the .NET Framework; it is the root of the type hierarchy.
Since it is a super class, Object defines some key methods. As follows:

Equals method - used to compare whether two instances are equal.
public virtual bool Equals(Object obj), compares whether the current instance is equal to obj;
public static bool Equals(Object objA,Object objB), compares whether the specified two instances are equal.

Finalize method - Allows an Object to attempt to release resources and perform other cleanup operations before Garbage Collection reclaims the Object.

GetHashCode method - Gets the Hash value of an object.

GetType method - Get the Type of the current instance.

MemberwiseClone method - creates a shallow copy of the current instance, that is, if the current instance has a value, the newly created instance only obtains the value of the value type, and the reference type does not obtain the value. .

ReferenceEquals method - compares two instances to see if they are the same, and has the same usage as static bool Equals(Object objA,Object objB).

ToString method - This is commonly used and is used to return the string of the current instance.
Object is a super class, so all classes in C# have these methods.

The following focuses on the Equals and ToString methods.
1. Object comparison
There are value types and reference types in C#. A simple understanding is that value types save the value of objects, while reference types are references to instances, similar to pointers in C language. Therefore, when using object comparison, the value type compares whether the values ​​of two objects are equal, and the reference type compares whether the specified reference refers to the same object. Of course, sometimes the instance values ​​pointed to by the reference types are compared to see if they are the same.
The following is the code for object comparison:

using System;
using System.Collections.Generic;
using System.Text;

namespace YYS.CSharpStudy.MainConsole.AboutObject
{
    public class Int32Value : ICloneable
    {
        //字段,定义字段最好赋上初值
        private int intValue = 0;

        /// <summary>
        /// 属性
        /// </summary>
        public int IntValue
        {
            get
            {
                return this.intValue;
            }

            set
            {
                this.intValue = value;
            }
        }

        /// <summary>
        /// 定义一个无参构造器
        /// </summary>
        public Int32Value() { }

        /// <summary>
        /// 带参数的构造器
        /// </summary>
        public Int32Value(int value)
        {
            this.intValue = value;
        }

        ///// <summary>
        ///// 实现ICloneable接口
        ///// </summary>
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
}

Call:

using System;
using YYS.CSharpStudy.MainConsole.AboutObject;

namespace YYS.CSharpStudy.MainConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明一个Int32Value类型的引用value1,指向一个实例
            Int32Value value1 = new Int32Value(30);

            //声明value2,指向value1,此时两个引用是指向一个实例的
            Int32Value value2 = value1;

            //使用==比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1 == value2 ? "相同" : "不相同"));//相同

            //调用Clone,复制一个value1的副本,赋值给value2
            //此时是两个实例了
            value2 = (Int32Value)value1.Clone();

            //使用==比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1 == value2 ? "相同" : "不相同"));//不相同

            //将value1赋给value2,此时他们指向同一个实例
            value2 = value1;

            //使用Equals比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1.Equals(value2) ? "相同" : "不相同"));//相同

            //调用Clone,复制一个value1的副本,赋值给value2
            //此时是两个实例了
            value2 = (Int32Value)value1.Clone();

            //使用Equals比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1.Equals(value2) ? "相同" : "不相同"));//不相同

            Console.ReadLine();
        }
    }
}

Result:

As can be seen from the code:

a. For reference types, the = operator passes the reference from one variable to another, so the variables on both sides of = refer to the same object;

b. For two variables that reference the same, use = = operator returns true;

c. The Clone method of an object generates a new instance and returns a reference to the instance. All field values ​​of the instance are the same as the original object, that is, the Clone method obtains a copy of the object. The protection method MemberwiseClone inherited from the Object class returns a copy of the current object;

d. For the object returned by the Clone method, its reference is different from the original object, and the == operator returns false;

e. The result of the Equals method inherited from Object is the same as the == operator. It just compares whether the current reference (this) and the reference saved by the parameter refer to the same object.
Based on the above code, rewrite the Equals method.

using System;
using System.Collections.Generic;
using System.Text;

namespace YYS.CSharpStudy.MainConsole.AboutObject
{
    public class Int32Value : ICloneable
    {
        //字段,定义字段最好赋上初值
        private int intValue = 0;

        /// <summary>
        /// 属性
        /// </summary>
        public int IntValue
        {
            get
            {
                return this.intValue;
            }

            set
            {
                this.intValue = value;
            }
        }

        /// <summary>
        /// 定义一个无参构造器
        /// </summary>
        public Int32Value() { }

        /// <summary>
        /// 带参数的构造器
        /// </summary>
        public Int32Value(int value)
        {
            this.intValue = value;
        }

        ///// <summary>
        ///// 实现ICloneable接口
        ///// </summary>
        public object Clone()
        {
            return this.MemberwiseClone();
        }

        /// <summary>
        /// 覆盖Equals方法
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            bool isEquals = Object.ReferenceEquals(obj, this);

            if (isEquals == false)
            {
                Int32Value value = obj as Int32Value;

                if (value != null)
                {
                    isEquals = value.intValue == this.intValue;
                }
            }
            return isEquals;
        }
    }
}

Call

using System;
using YYS.CSharpStudy.MainConsole.AboutObject;

namespace YYS.CSharpStudy.MainConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明一个Int32Value类型的引用value1,指向一个实例
            Int32Value value1 = new Int32Value(30);

            //声明value2,指向value1,此时两个引用是指向一个实例的
            Int32Value value2 = value1;

            //使用==比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1 == value2 ? "相同" : "不相同"));//相同

            //调用Clone,复制一个value1的副本,赋值给value2
            //此时是两个实例了
            value2 = (Int32Value)value1.Clone();

            //使用==比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1 == value2 ? "相同" : "不相同"));//不相同

            //将value1赋给value2,此时他们指向同一个实例
            value2 = value1;

            //使用Equals比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1.Equals(value2) ? "相同" : "不相同"));//相同

            //调用Clone,复制一个value1的副本,赋值给value2
            //此时是两个实例了
            value2 = (Int32Value)value1.Clone();

            //使用Equals比较
            Console.WriteLine(string.Format("value1和value2 {0}", value1.Equals(value2) ? "相同" : "不相同"));//相同

            Console.ReadLine();
        }
    }
}

Result:

Modified code:
Covers the Equals method, and the program running result is different: Equals is no longer compared Check whether the object references saved by the two variables are the same, but compare whether the objects referenced by the two variables have the same attribute values.
The execution process of Equals after overwriting is as follows:
Let’s take a look at the specific execution process of the Equals method after overwriting:

a. Use the Object static method ReferenceEquals to compare the parameter obj and the current object reference (this ) are the same, if the reference is the same, it must be the same object;
b. If the variable obj is not the same as the current reference, use the as operator to try to convert the obj type to the same type as the current object. Successful conversion means obj The variable refers to the same object as the current object class. The as operator converts the reference of the object, otherwise it returns null. Only objects of the same type need to be compared. Objects of different types must be different objects;
c. If as If the operator successfully converts the object, it will further compare whether the current object reference (this) and the field value of the object referenced by the parameter obj are equal.
It can be seen from the above two pieces of code:
== and the Equals method of the Object class both compare whether the references of the objects are the same, and do not compare whether the fields of the objects are equal; and the Equals method can be overridden, In order to allow it to perform equivalence comparison or other comparisons on the fields of the object.
Therefore, if you need to compare two C# reference type variables, you can use the == operator unless you are sure that what needs to be compared is an object reference. Otherwise, you should use the Equals method of the object to prevent the class to which the object belongs from overriding this method.

    上面是引用类型的比较,相对来说,值类型的比较就比较纯粹。值类型是不存在引用的,所以值类型就是比较两个对象值是否相等。当然如果覆盖了Equals方法就除外了。不过一般情况下,我们无需覆盖Equals方法。对于引用类型来说,等值比较就是比较对象的引用,引用不同的两个对象应该就是不同的对象;对于值类型来说,比较的就是所有字段的值,字段值不同的两个对象是不同的对象。只有在特殊情况下,才需要覆盖Equals方法,已定义某个类特殊的对象比较方法。
对于覆盖Equals方法,要注意:
注意:理论上可以用任意代码覆盖Equals方法,但要保证如下原则:
a、Equals只能用于对象比较,不能做其它任何用途;
b、对于两个已存在的对象,在对象未作任何改变的情况下,无论任何时候调用Equals方法,返回的结果应该是一样的;
c、对于对象a和b,则a.Equalse(b)和b.Equals(a)返回的结果应该是一样的;
d、覆盖了Equals方法,同时要覆盖GetHashCode(方法),这个后面再详细说明。

二、ToString()
代码:

   public class Int32Value : ICloneable
    {
        //字段,定义字段最好赋上初值
        private int intValue = 0;

        /// <summary>
        /// 属性
        /// </summary>
        public int IntValue
        {
            get
            {
                return this.intValue;
            }

            set
            {
                this.intValue = value;
            }
        }

        /// <summary>
        /// 定义一个无参构造器
        /// </summary>
        public Int32Value() { }

        /// <summary>
        /// 带参数的构造器
        /// </summary>
        public Int32Value(int value)
        {
            this.intValue = value;
        }

        ///// <summary>
        ///// 实现ICloneable接口
        ///// </summary>
        public object Clone()
        {
            return this.MemberwiseClone();
        }

     
        /// <summary>
        /// 重写ToString方法
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return this.intValue.ToString();

            //return "重写ToString";
        }
    }

 调用:

     class Program
    {
        static void Main(string[] args)
        {
            Int32Value value = new Int32Value(30);

            Console.WriteLine(value.ToString());//30

            //Console.WriteLine(value.ToString());//重写ToString

            Console.ReadLine();
        }
    }

可以看出,ToString方法可以用任意代码覆盖,只要返回string即可,但是在覆盖时也要返回符合需求的返回值。

以上就是C#基础知识整理:基础知识(12) 超类Object 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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
The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment