开发者

Why Interface support multiple inheritance and class doesnt in c# [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Why C# doen't support multiple inheritance

Should C# include multiple inheritance?开发者_如何转开发

i like to what is reason for interface support multiple inheritance and class doesnt support


I would rather 'negate' your statement.. "interface support multiple inheritance".

Interface is NOT actually inheritance, it is JUST a "contract" of service/behavior that a class abides with.

By implementing an interface a class does NOT inherit anything per se.

And since a class/entity can bind with multiple contracts (behaviours), we can implement multiple interfaces in a class.


Because these are conceptually two totally different things.

If you inherit from a class, you inherit the code of the base class. If you implement (not inherit!) an interface, you force your implementing class to have some predefined method/event/property signatures.

While multiple inheritance for classes is a notorious source of errors and confusion, having many interfaces in a class' inheritance list is about combining various behavioural aspects, and as such it is an important instrument for component-based programming.

Or, in other words: It is an implementation of the Favour Composition over Inheritance design principle.

Thomas


I'd be very interested in a more authoritative answer, but here's my take.

In languages that support multiple inheritance, the key ambiguity that is (arguably) unsatisfactorily resolved is what happens when you subclass from two types that both define a method with the same signature. For example:

public class BaseClass1 
{
    public string SomeMethod() 
    {
        return "Implementation1";
    }
}

public class BaseClass2 
{
    public string SomeMethod() 
    {
        return "Implementation2";
    }
}

public class MySuclass : BaseClass1, BaseClass2 
{
}

Now what does the following return?

MySubclass mySubclass = new MySubclass();
string s = mySubclass.SomeMethod();

In C#, explicit interface implementation allows you to easily resolve this by definining both. After converting BaseClass1 and BaseClass2 to interfaces, we can have

public class MySuclass : IBaseClass1, IBaseClass2 
{
    string IBaseClass1.SomeMethod()
    {
        return "Implementation1";
    }

    string IBaseClass2.SomeMethod()
    {
        return "Implementation2";
    }
}

The key of course being that there is no ambiguity with this syntax as it's not possible to access SomeMethod without first casting the target to either IBaseClass1 or IBaseClass2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜