对接口继承感到困惑

时间:2018-11-08 21:45:50

标签: vb.net interface

我知道我应该更广泛地使用它,但是我们的代码只有少数几个接口,所以我对它们有些不了解。这是我的问题。在文件一中,我有这个:

Friend Interface IDateRow
    Property Name() As String
    ...
End Interface
Friend Interface IAmountRow
    Property StartDate() As IDateRow
    Property EndDate() As IDateRow
    ...
End Interface

在文件2中,我有这个:

Friend Class DateRow
    Inherits DtaRow
    Implements IDateRow
    Friend Property Name() As String Implements IDateRow.Name
    ...
End Class

到目前为止,一切都很好。现在...

Friend Class AmountRow
    Inherits DtaRow
    Implements IAmountRow
    Friend Property StartDate() As DateRow Implements IAmountRow.StartDate

这行不通-它说:

'StartDate' cannot implement 'StartDate' because there is no matching property on interface 'IAmountRow'.

我是否认为这是因为它返回DateRow而不是IDateRow? DateRow实现IDateRow,因此似乎应该合法。

我知道我在这里错过了一些愚蠢的东西...

2 个答案:

答案 0 :(得分:3)

您必须使用与接口完全相同的类型来实现属性-因此

Friend Property StartDate() As DateRow Implements IAmountRow.StartDate

应该是

Friend Property StartDate() As IDateRow Implements IAmountRow.StartDate

答案 1 :(得分:0)

接口是身份。假设IDateRow放置在“ A.dll”中,而实现它的DateRow放置在“ B.dll”中。并假设A.dll中存在一个输入IDateRow实例的函数。由于A.dll没有引用B.dll,因此它不知道什么是DateRow。因此,它期望一个实例的ID为“ Property StartDate()as IDateRow”而不是DateRow。

编辑-我试图回答@MauryMarkowitz的评论:

我认为您想要一个抽象类。我已经用c#编写了一个示例,但我想它与vb类似。

//A.dll -> has no reference
public abstract class Vehicle 
{
    public abstract double Mass();
    public abstract double Force();

    public double Acceleration()
    {
        return this.Force() / this.Mass();
    }
}
public interface ICar
{
    double MaxGroundSpeed();
}
public interface IPlane
{
    double MaxAirSpeed();
}


//B.dll -> has a reference to A.dll
public class Ferrari360 : Vehicle, ICar
{
    public override double Force()
    {
        return 400;
    }
    public override double Mass()
    {
        return 1350;
    }
    public virtual double MaxGroundSpeed()//Ferrari likes to make good cars, better, so this should be virtual.
    {
        return 282;
    }
}
public class Ferrari360GT:Ferrari360
{
    public override double Mass()
    {
        return 1100;
    }
    public override double MaxGroundSpeed()
    {
        return 300;
    }
}
public class Concorde : Vehicle, IPlane
{
    public override double Force()
    {
        throw new ClassifiedInformationException();
    }
    public override double Mass()
    {
        return 92080;
    }
    public double MaxAirSpeed()
    {
        return 2180;
    }
}
public class DeLoreanTimeMachine : Vehicle, ICar, IPlane
{
    public override double Force()
    {
        return 130;
    }
    public override double Mass()
    {
        return 1230;
    }
    public double MaxAirSpeed()
    {
        return 299792;
    }
    public double MaxGroundSpeed()
    {
        return 88;
    }
}

使用示例:

Ferrari360 greatCar = new Ferrari360();
Console.WriteLine(greatCar.Acceleration());