【问题标题】:Inherit from abstract class with properties of another type (.NET 3.5, C#)从具有另一种类型(.NET 3.5、C#)的属性的抽象类继承
【发布时间】:2011-05-17 16:36:48
【问题描述】:

我有以下 3 个课程:

public class BaseProperty1{
    public string Property1 {get; set;}
}

public class ChildProperty1 : BaseProperty1 {

}

public abstract class Base{
    public abstract BaseProperty1 bp1 {get; set;}
}

我正在尝试从 Base 派生以下类:

public class Child : Base{
    public ChildProperty1 bp1 {get; set;}
}

但我收到一个错误,即“set”和“get”方法未实现。只是我使用的语法还是我的思维方式不对?

谢谢!

【问题讨论】:

  • 你能添加准确的错误文本吗?
  • 'Child' 没有实现继承的抽象成员 'Base.BaseProperty1.set'

标签: c# inheritance abstract-class automatic-properties


【解决方案1】:

您将无法使用自动属性,因为您必须完全匹配基类的类型。你必须走老式的路:

public abstract class Child : Base
{
    private ChildProperty1 _bp1;

    public BaseProperty1 bp1
    {
        get { return _bp1; }

        // Setter will be tricky. This implementation will default to null
        // if the cast is bad.
        set { _pb1 = value as ChildProperty1; }
    }
}

您也许还可以使用泛型来解决问题:

public abstract class Parent<TProp> where TProp : BaseProperty1
{
    public abstract T bp1 { get; set; }
}

public abstract class Child : Parent<ChildProperty1>
{
    public ChildProperty1 bp1 { get; set; }
}

【讨论】:

  • 我正在尝试实施您的第一个建议,但我仍然遇到同样的错误。我还能在 Base 类中使用 AutoProperties 吗?
【解决方案2】:

如果将方法或属性标记为抽象,则必须在继承的类中实现它。 您可以隐藏旧属性(基类中的 bp1)并使用另一种返回类型编写新属性,如下所示:

public abstract class Base{
    public BaseProperty1 bp1 {get; set;} //without abstract identifier
}

public class Child : Base
{
       public new ChildProperty1 bp1 { get; set; } // with new modifier
}

【讨论】:

  • 但是我需要在我的子类中有一个同名但另一种类型(childProperty 类型)的属性。那行得通吗?
  • 我已经修改了我的答案。现在应该没问题了
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2013-06-10
  • 2021-06-13
  • 2023-04-03
  • 2013-04-18
相关资源
最近更新 更多