c# - 从具有另一种类型属性的抽象类继承(.NET 3.5,C#)

标签 c# inheritance abstract-class automatic-properties

我有以下 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”方法没有实现。是我使用的语法不对还是我的思维方式不对?

谢谢!

最佳答案

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

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; }
}

关于c# - 从具有另一种类型属性的抽象类继承(.NET 3.5,C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6034132/

相关文章:

c# - 操作方法的细粒度访问控制

c++ - 对C++继承感到困惑

c# - 如何在C#中继承WPF控件并同时使用泛型类?

interface - 在 Haxe 中,当子类中未在 "abstract"父类(super class)中定义方法时,如何强制执行子类中的方法声明?

c# - 同时使用抽象类和接口(interface)的原因? (抽象类实现接口(interface))

java - 如何为子类提供静态字段?

c# - 在 ASP.NET MVC 操作中获取复选框值

c# - 使用 double.TryParse 奇怪行为解析数字

c++ - 使用编译时已知的类型避免模板冗长和动态多态性

c# - 使用子目录时 Javascript 和 CSS 文件不起作用