简体   繁体   中英

Why can't a derived class override base class' interface type abstract property with a type that extends that interface?

In the following code, compiler complains about B not implementing TestProperty of abstract class A . ITest2 is derived from ITest1 so it implements everything ITest1 has. Why is this not possible?

public interface ITest1 { }
public interface ITest2 : ITest1 { }

public abstract class A
{
    public abstract ITest1 TestProperty { get; set; }
}

public class B:A
{
    public override ITest2 TestProperty { get; set; }
}

This wouldn't be safe since you could do:

interface ITest3 : ITest1 { }
public class Test3 : ITest3 { }

A b = new B();
b.TestProperty = new Test3();

however Test3 does not implement ITest2 as required by B .

Make A class generic

Public abstract class A<TTest>
    Where TTest : ITest1
 {
    Public abstract TTest TestProperty {get; set;}
 }

 Public class B : A<ITest2>
 {
 ....
 }

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