【问题标题】:Not entering Equals() method in a class derived from Object不在从 Object 派生的类中输入 Equals() 方法
【发布时间】:2022-01-12 21:39:02
【问题描述】:

在确切的设置中:

namespace NS
{
    class Program
    {
        static void Main(string[] args)
        {
            Object obj1 = new A();
            Object obj2 = new A();
            Console.WriteLine(obj1.GetType());
            Console.WriteLine(obj2.GetType());

            Console.WriteLine(obj1.Equals(obj2)); // why not entering A::Equals(A a)
            Console.ReadLine();
        }
    }
    class A
    {
        int x;
        public bool Equals(A a)
        {
            Console.WriteLine("enters Equals");
            return this.x == a.x;
        }
    }
}

我有来自 C# 控制台应用程序的输出:

NS.A
NS.A
False

问题:如果ojb1obj1 是NS.A 类型,为什么不输入public bool Equals(A a)

Console.WriteLine(obj1.GetType()); 是关于真实对象类型的“谎言”。我很困惑?

我想从代码中调用A.Equals(A) 方法,即使Object obj1 = new A();

我知道我可以用A obj1 = new A(); 解决这个问题,但我不明白为什么GetType() 返回A 而我不能调用A.Equals(A)

【问题讨论】:

标签: c# class inheritance methods gettype


【解决方案1】:

您需要让它知道它是覆盖而不是创建新函数。

    public override bool Equals(object a)
    {
        Console.WriteLine("enters Equals");
        return ((A)this).x == ((A)a).x;
    } 

您的代码正在创建两个对象 obj1 和 obj2。在询问对象类型时,它返回类型 A,因为它是 obj1 和 obj2 的类型。但是,您在对象变量中包含 obj1 和 obj2。因此,当您调用 obj1.Equals 时,它正在调用 Object 的 Equals 方法。您可以使用 override 命令覆盖它并采用相同的参数,或者您可以明确告诉您的程序您希望它使用 (A) 类方法。

    class Program
    {
        static void Main(string[] args)
        {
            Object obj1 = new A();
            Object obj2 = new A();
            Console.WriteLine(obj1.GetType());
            Console.WriteLine(obj2.GetType());

            Console.WriteLine(obj1.Equals(obj2)); // why not entering A::Equals(A a)
            
            Console.WriteLine(((A)obj1).Equals((A)obj2));
            A a1 = new A();
            A a2 = new A();
            
            Console.WriteLine(a1.Equals(a2));
            
            Console.ReadLine();
        }
    }
    class A
    {
        int x;
        public bool Equals(A a)
        {
            Console.WriteLine("enters Equals");
            return ((A)this).x == ((A)a).x;
        }
    }

返回

A
A
False
enters Equals
True
enters Equals
True

这里有更多关于overriding的信息。

干杯!

【讨论】:

  • 这确实解决了问题。为什么我错过了这个概念?实际上我正在解决的原始问题有public new bool Equals(object a),我很震惊编译器吞下了它。你能详细说明什么时候方法可以是new吗?
  • new 修饰符隐藏一个可访问的基类方法 -(添加了重点)-来自 Knowing When to Use Override 和 New Keywords (@ 987654322@)
猜你喜欢
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 2013-07-25
  • 1970-01-01
  • 2016-07-12
相关资源
最近更新 更多