开发者

Overriding a virtual method with a generic return type

开发者 https://www.devze.com 2023-04-12 11:18 出处:网络
Consider these two abstract classes.MyClass2 extends my BaseClass and overrides a virtual method.Note it also defines TValue of MyBaseClass as IList...

Consider these two abstract classes. MyClass2 extends my BaseClass and overrides a virtual method. Note it also defines TValue of MyBaseClass as IList...

public abstract class MyBaseClass<TKey, TValue>
{
    public virtual IList<TValue> DoSomeStuff()
    {
        IList<TValue> result;
      开发者_如何学Go  ....
        return restult;
    }
}

public abstract class MyClass2<TKey, TValue>: MyBaseClass<TKey, IList<TValue>>
{
    public override IList<TValue> DoSomeStuff()
    {
        IList<TValue> result;
        ....
        return restult;
    }
}

This code does not compile. The complaint is on the return type of MyClass2.DoSomeStuff. The error is "Cannot change return type when overriding method "IList<TValue> MyClass2<TKey, TValue>.DoSomeStuff()"

I'm not clear as to why this is wrong. Why wouldn't the compile or .net consider TValue for the overriden method to be that of MyClass2?


The problem's in your base class part:

public abstract class MyClass2<TKey, TValue>: MyBaseClass<TKey, IList<TValue>>

Replace the IList<TValue> with TValue and it will work - the method already returns an IList.


The TValue parameter of your base class, as inherited by your subclass, is actually IList<TValue> as declared by your subclass. The inner TValue pertains to your subclass.

So if you're trying to override the existing virtual method that belongs to the base class, the return type is actually expected to be IList<IList<TValue>>; that is, an IList of the TValue that belongs to your base class, not the subclass.


You're getting the error because TValue in the child class is actually IList<TValue> in the base class so the method signature (as your base class would see it) would be IList<IList<TValue>> which obviously doesn't match the virtual method's signature.

To get matching types, you would have to change the signature:

public override TValue DoSomeStuff()
{
    TValue result;

    return result;
}
0

精彩评论

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

关注公众号