使用C#的多重继承 [英] Multiple inheritence with c#

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

问题描述



我有一个问题,我有两个接口

Hi

I have one problem i have two interfaces

interface test1
{
void show();
}
interface test2
{
void show();
}

class testing: test1,test2
{
// How to call test1 and test2 method
}



有人可以帮我吗?

问候
S. keshaavan



Can any one help me please?

Regards
S. keshaavan

推荐答案

OriginalGriff:显式接口方法不应公开(如果声明任何访问修饰符,则会出现编译错误,但我想知道您是否检查了代码在您写答案之前?),但是默认情况下它是私有的.原因是这些方法应该通过接口引用而不是通过类的对象进行访问.

因此,这就是我们如何实现(显式实现)碰巧具有相同方法的接口.

OriginalGriff: explicit interface methods should not be public (you will get compile error if you declare any access modifier, but I wonder did you check your code before you wrote the answer?) but it is private by default. The reason being is that these methods should be accessible via the interface reference not via the object of the class.

So, here is how we implement (explicit implementation) the interfaces which happened to be having same methods.

class testing : test1, test2
    {

        void test1.show()
        {
            MessageBox.Show("From interface test1");
        }

        void test2.show()
        {
            MessageBox.Show("From interface test2");
        }
    }



这是您访问它们的方式:



And here is how you access them:

testing t = new testing();

            test1 t1 = t;
            test2 t2 = t;

            t1.show();
            t2.show();


您不能-它们是接口.
接口没有定义任何代码,它们只是通过实现属性和方法声明派生类必须遵守的协定.

您必须在testing类中实现show方法,然后如果需要显式调用它,请将测试实例转换为test1或test2:
You can''t - they are interfaces.
Interface do not define any code, they just declare a contract that the derived class must adhere to by implementing the properties and methods.

You would have to implement the show method in the testing class and then if you needed to explicitly call it, cast your testing instance to test1 or test2:
interface test1
    {
    void show();
    }
interface test2
    {
    void show();
    }

public class testing : test1, test2
    {
    // How to call test1 and test2 method
    public testing()
        {
        ((test1)this).show();
        ((test2)this).show();

        }

    public void test1.show()
        {
        throw new NotImplementedException();
        }

    public void test2.show()
        {
        throw new NotImplementedException();
        }
    }


我本来应该先看一下Google.这已经无限次地被问到了.

https://www.google. com/search?sourceid = chrome& ie = UTF-8& q = Multiple + heritence + c%23& hl = zh_CN [ http://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp [ ^ ]
I would have first looked at Google. This has been asked infinte times already.

https://www.google.com/search?sourceid=chrome&ie=UTF-8&q=Multiple+inheritence+c%23&hl=en[^]

Anyway, this thread should help.

http://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp[^]


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

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