下面的类将如何编译以及任何错误。 [英] How the below classes will compile withought any error.

查看:49
本文介绍了下面的类将如何编译以及任何错误。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看继承自absract类Customer的B类并实现接口CC。这两个都有相同名称的方法。



它覆盖了抽象类的OpenGate()方法。



那么接口的方法怎么样。虽然我们没有实现CC接口的OpenGate()方法,但这个类getiing编译了吗?



什么我试过了:



界面CC

{

void OpenGate();



}





公共抽象类客户

{

public virtual void OpenGate()

{

Console.WriteLine(Abstarct);



}



}

公共类B:客户,CC

{

public override void OpenGate()

{

Console.WriteLine(B);



}







}







public C级:B

{

公共覆盖无效OpenGate()

{

Console.WriteLine(C );



}







}

Look at class B which inherits from absract class Customer and implement the interface CC. Both of these have Method with same name .

it's overriding the OpenGate() method of abstract class.

Then what about the method from the interface.How this class getiing compiled though we are not implementing OpenGate() method of CC interface??

What I have tried:

interface CC
{
void OpenGate();

}


public abstract class Customer
{
public virtual void OpenGate()
{
Console.WriteLine("Abstarct");

}

}
public class B : Customer, CC
{
public override void OpenGate()
{
Console.WriteLine("B");

}



}



public class C : B
{
public override void OpenGate()
{
Console.WriteLine("C");

}



}

推荐答案

因为OpenGate方法具有与抽象类和接口所需的签名相同的签名,所以它满足这两个要求,因此编译好。如果您需要执行不同的方法,则需要明确实现接口版本:

Because the OpenGate method has the same signature as that required by both the abstract class and Interface, it satisfies both requirements so it compiles OK. If you need different methods to be executed, then you need to explicitly implement the interface version:
public class B1 : Customer, CC
    {
    public override void OpenGate()
        {
        Console.WriteLine("B1: Customer");
        }
    void CC.OpenGate()
        {
        Console.WriteLine("B1: CC");
        }
    }
public class B2 : Customer, CC
    {
    public override void OpenGate()
        {
        Console.WriteLine("B2");
        }
    }

然后,您可以同时使用它们:

Then, you can use them both:

B1 b1 = new B1();
CC cc = b1;
b1.OpenGate();
cc.OpenGate();
B2 b2 = new B2();
cc = b2;
b2.OpenGate();
cc.OpenGate();

您将获得:

And you will get:

B1: Customer
B1: CC
B2
B2


这篇关于下面的类将如何编译以及任何错误。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆