c# - 为什么重载不起作用?

标签 c# overloading

为什么程序启动后会显示C::Foo(object o)

using System;

namespace Program
{
    class A
    {
        static void Main(string[] args)
        {
            var a = new C();
            int x = 123;
            a.Foo(x);
        }
    }

    class B
    {
        public virtual void Foo(int x)
        {
            Console.WriteLine("B::Foo");
        }
    }

    class C : B
    {
        public override void Foo(int x)
        {
            Console.WriteLine("C::Foo(int x)");
        }

        public void Foo(object o)
        {
            Console.WriteLine("C::Foo(object o)");
        }
    }
}

我不明白为什么当你调用 C::Foo 时,使用 object 选择方法,而不是使用 intB 类是什么,该方法被标记为覆盖?

C类中,有两个同名不同参数的方法,是不是重载了?为什么不?在父级中覆盖其中一种方法是否重要?它以某种方式禁用过载?

最佳答案

看看Member lookup

First, the set of all accessible (Section 3.5) members named N declared in T and the base types (Section 7.3.1) of T is constructed. Declarations that include an override modifier are excluded from the set. If no members named N exist and are accessible, then the lookup produces no match, and the following steps are not evaluated.

所以根据这个,它会使用

public void Foo(object o)

首先

关于c# - 为什么重载不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21718706/

相关文章:

使用回调重载 JavaScript

c# - 任意长度字符串的基数排序

c# - 为什么 System.Net.HttpListener 创建一个新进程?

c++ - 'default-initialization in copy-initialization context' 在 C++ 中是什么意思?

c++ - 对 std::optional 的转发引用构造函数的约束

java - 从Java中的泛型方法调用重载方法

c++ - 比较binary_search的功能

c# - pinvoke 编码 double 类型的二维多维数组作为 C# 和 C++ 之间的输入和输出

c# - 在不知道元素类型的情况下将项目添加到列表中

c# - public IEnumerator GetEnumerator() 的返回类型?