简体   繁体   中英

Why type constraint in a generic class is not enough for the compiler when implementing an interface?

If the type constraint guarantees that T implements IParameter, why cannot I implement IMain's Method with T as an argument?

interface IMain
{
    void Method(IParameter parameter);
}

interface IParameter
{
}

class Implementation<T> : IMain where T : IParameter
{
    //public void Method(IParameter parameter) { }//accepted implementation
    public void Method(T parameter) { }//leaves the class with a "does not implement member..." compiler error
}

If the type constraint guarantees that T implements IParameter, why cannot I implement IMain's Method with T as an argument?

Let's assume for a second that that's legal and see what happens in this scenario.

Suppose, we have two classes that implement IParameter :

class Param1 : IParameter { }
class Param2 : IParameter { }

Then, we create the following object:

var p1 = new Implementation<Param1>();

At this point, p1.Method would only take an argument of type Param1 . So, attempting to do something like this won't work:

p1.Method(new Param2());  // This is illegal, as expected.

Now, let's cast p1 to IMain and try again:

var asIMain = (IMain)p1;
asIMain.Method(new Param2()); // What should happen here?!

On one hand, we have IMain whose Method takes an IParameter argument, so it should allow a Param2 object. But on the other hand, the underlying type of asIMain is Implementation<Param1> whose Method only accepts a Param1 argument. The compiler is smart enough to prevent this situation from happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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