c# - 多个派生抽象类?

标签 c# .net c#-4.0 abstract-class multiple-inheritance

我必须创建一个包含类(class)类别的类(class)管理系统:

Cooking, sewing and writing courses

cookingwriting 各有 2 门类(class)(意大利语、海鲜、创意写作和商业写作)。这将创建派生摘要:

abstract course -> abstract cooking -> concrete seafood

抽象的cooking和writing有共同的领域和一些共同的方法,但是它们也有抽象在基类中的抽象方法。

这可以用 C# 完成吗?如果我使派生抽象类方法抽象 Visual Studio 说它们隐藏了基类抽象,然后具体类方法有错误说基类必须是抽象的(它是但不能注册)。我一直在寻找答案。我知道 C# 中使用了单一继承,但继承沿链进行。最佳答案是什么?

这是一个代码片段 - 我希望它能澄清问题:

public abstract class Course
{
    public abstract void AddStudent(StudentName sn, int f);
    public abstract decimal CalculateIncome();
}

public abstract class WritingCourse : Course
{
    public void AddStudent(StudentName sn, int f)
    {
     //Add student
    }
    public abstract decimal CalculateIncome(); // can only be claculated in concrete
}

public class BusinessWritCourse : WritingCourse
{
    public void AddStudent(StudentName sn, int f):
    base(sn, false){}

    public decimal CalculateIncome()
    {
       return //do stuff
    }
}

public class SewingCourse : Course
{
    public override void AddStudent(StudentName sn, int f)
    {
        //do stuff
    }

    public override decimal CalculateIncome()
    {
       return //do stuff
    }
}

最佳答案

if I make the derived abstract class methods abstract Visual Studio says they hide the base class abstract and then the concrete class methods have errors saying the base class must be abstract (it is but must not register)

如果你的基类 'A' 有一个抽象方法 'b()' 那么你不必在 B : A 中再次声明 'b()' 为抽象,让 C : B 覆盖它,只是不要使用它。即使您在类 B 中覆盖了“b()”方法,您也可以在类“c()”中再次覆盖它(甚至使用 base.(); 来执行 B 的实现。

部分代码:

public abstract class A{
    public abstract void b();
}

public class B : A{
    public override void b() { //do stuff }; //overrides b from a
    public virtual void c() { //do stuff }; //creates an implemented method c in B that can be overriden by childs.
    public void d() { //do stuff};
}

public class C : B{
    public override void b() { //do stuff}; //overrides b from A, works!
    public override void c() {//do stuff}; //overrides c from B, works!
    public override void d() {//do stuff}; //doesn't work since d from B isn't abstract or virtual (hides it)
    public new void d() {//do stuff}; //works, hides d, but when you use inheritance this method will not be called, instead B's d() method will be called, only if you see C as  the specific class C this will work
}

还要澄清:声明为抽象的方法必须被覆盖(就像在接口(interface)中一样,并且只能由声明抽象方法的类的直接子类覆盖)。声明为 virtual 的方法可以被覆盖,但不是必须的。

关于c# - 多个派生抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6531041/

相关文章:

c# - 使用 System.IO.Compression.ZipArchive 时避免 MemoryStream.ToArray()

.net - ASP.Net 配置页在哪里?

c# - 用于 .NET/Oracle 数据交换的关联数组与 UDT 表

c# - 获取程序集而不实例化它们

c# - 在字典中添加复杂的键!对性能有影响吗

c# - 从字面上打印带有前导 0 的整数

c# - 有没有一种简短的方法来替换 C# 中字符串中的两个字符?

c# - 如何在抽象类中引用单一行为类

.net - 使用 PropertyGrid 设置 PerformanceCounter

c# - 迭代字典并向每个字典值添加一个值