面试问题 - C#,多重继承,接口 [英] Interview question - C#, multiple inheritance, interfaces

查看:133
本文介绍了面试问题 - C#,多重继承,接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All,



最近我在其中一次采访中被问到一个问题:



有一个dll,有2个班级

Hello All,

Recently i was asked a question in one of the interviews:

There is a dll, which has 2 classes

Class A
{
Method A(){...}
}

Class B
{
Method B(){...}
}





在另一个程序中还有另一个C类

现在我怎样才能继承CLass B& A类中的A,没有修改dll中的任何内容?



那么如何实现这个目标?

请帮我解答这个愚蠢的问题。



我尝试了什么:



多个C#不支持继承,所以我不能给C类:B,A

由于我无法修改dll中的任何内容,我也无法实现接口..



In a separate program there is another Class C
Now how can i inherit both CLass B & A in Class C, without modifying anything in the dll?

So how to achieve this?
Please help me in getting the answer to this silly question.

What I have tried:

As multiple inheritance is not supported in C# so I cannot give Class C:B,A
And as i cannot modify anything in the dll, i cannot implement interfaces too..

推荐答案

取决于。

您可以说:完全没有,因为C#中不存在多重继承。

您可以说:让我们使用一些招数。像那样:

Depends.
You could say: not at all, as multiple inheritance does not exist in C#.
You could say: let's use some tricks. Like that:
Interface IA
{
    Method A();
}
Interface IB
{
    Method B();
}



然后让我们添加一些实现接口的包装器,然后直接传递到原始类:


Then let's add some wrappers which implement the interfaces and just pass thru to the original classes:

class AWrapper : IA
{
    A _Instance;
    AWrapper()
    {
        _Instance = new A();
    }

    Method A ()
    {
        _Instance.A();
    }
}

和B类似。

现在我们可以更改C:

and similar for B.
Now we can change C:

class C: IA, IB
{
    IA _AInstance;
    IB _BInstance;
    C()
    {
        _AInstance = new AWrapper();
        _BInstance = new BWrapper();
    }

    Method A()
    {
        _AInstance.A();
    }

    Method B()
    {
        _BInstance.B();
    }
}

好吧,不完全是继承,而是聚合。

Well, not exactly inheritance, rather aggregation.


我的答案是你不能。一些面试官会问你这些问题,以测试你的信心,看看你是否有真正的知识,或者只是试图在面试过程中进行游戏。
My answer would be that you can't. Some interviewers will ask you these kinds of questions to test your confidence and see if you have genuine knowledge or are just trying to game the interview process.


这篇关于面试问题 - C#,多重继承,接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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