简体   繁体   English

c#oops为什么不在示例代码中打印d

[英]c# oops why its not printing d in the sample code

Below code gives the output as "abc". 下面的代码将输出显示为“ abc”。

Please can someone explain why its not printing "d" 请有人可以解释为什么它不打印“ d”

public class a
{
    public void m1(a obj)
    {
        Console.WriteLine("a");
    }
}

public class b :a
{
    public void m1(b obj)
    {
        Console.WriteLine("b");
    }
}

public class c: b
{
    public void m1(c obj)
    {
        Console.WriteLine("c");
    }
}

public class d: c
{
    public void m1(d obj)
    {
        Console.WriteLine("d");
    }
}

class MainRunning
{
    static void Main(string[] args)
    {
        a a1 = new a();
        b b1 = new b();
        c c1 = new c();
        d d1 = new d();

        d1.m1(a1);
        d1.m1(b1);
        d1.m1(c1);

        Console.ReadLine();
    }
}

The method printing d is awaiting the instance of type d as its argument. 打印d的方法正在等待类型d的实例作为其参数。 No of your calls passes d to the method called m1 , so other overloads are used. 您的调用没有一次将d传递给名为m1的方法,因此使用了其他重载。

You can call d1.m1(d1) , which will resolve in m1(d obj) method call, which will write d into your console. 您可以调用d1.m1(d1) ,它将在m1(d obj)方法调用中解析,该方法调用会将d写入控制台。

You have 4 methods with the same name but different argument lists. 您有4个名称相同但参数列表不同的方法。 You call three of them, but not the fourth. 您呼叫其中三个,但不呼叫第四个。

It's because you don't call 因为你不打电话

d1.m1(d1);

When you call d1.m1(b1); 当您呼叫d1.m1(b1); then only method that can be run with that param (b1) is the one contained in b class. 那么只有可与该参数(b1)一起运行的方法才是b类中包含的方法。
And for very of the three methods you run, only one class at a time can handle it and this class is not d class which accepts a different parameter type!! 对于您运行的三种方法中的大多数,一次只能处理一个类,而该类不是d类型 ,它不接受其他参数类型!

Please see below: 请看下面:

class MainRunning
{
    static void Main(string[] args)
    {
        a a1 = new a();
        b b1 = new b();
        c c1 = new c();
        d d1 = new d();

        d1.m1(a1);
        d1.m1(b1);
        d1.m1(c1);
        d1.m1(d1); // <== ?

        Console.ReadLine();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM