C#中的继承不起作用

本文关键字:不起作用 继承 | 更新日期: 2023-09-27 18:21:35

我已经开始学习C#了,但现在我有点困惑,因为我遇到了一些问题。我正在尝试将一个类继承到另一个类,但它不起作用。上面写着"你没有正确的参数"所以,有一个代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication15 // Base class
{
    public class cakes
    {
        public int cakes_for;
        public cakes(int number) // constructor
        {
            cakes_for = number;
        }
        public int cakes_get // get value
        {
            get
            {
                return cakes_for;
            }   
            set
            {
                cakes_for = value;
            }
        }
        public static int cakes_plus_number(int n) // number plus constant
        {
            return n + 42;
        }
    }
    }

namespace ConsoleApplication15 // Derived Class
{
    public class Class2 : cakes // inheritance test
    {
        public int cakeses;
        public int Size { get; set; }
    }
}

C#中的继承不起作用

cakes没有无参数构造函数,因此任何派生类型都必须显式调用基类的构造函数之一。Class2需要用number的值来调用构造函数cakes(int number),因为没有它就无法实例化基类cakes。您可以通过派生类中构造函数签名后的语法: base()访问基类构造函数。示例:

public class Class2 : cakes
{
    public Class2(int number) : base(number) { }
    public int cakeses;
    public int Size { get; set; }
}

示例2:

public class Class3 : cakes
{
    public Class3() : base(8) { }
}

您应该为派生类添加一个构造函数,如下所示:

public class Class2 : cakes // inheritance test
{
    public Class2(int number) : base(number)
    {}
    public int cakeses;
    public int Size { get; set; }
}

需要注意的几点:

  • 用注释标记的类实际上是名称空间,而不是一回事。

  • 我建议研究一下大写风格,因为在你的例子中到处都是。

我稍微修改了您的代码。我还展示了如何在Form1()构造函数中实例化和使用它。当然,这不是把它放在最终版本中的正确位置,但它应该编译和执行,让你了解这个过程。

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        cake2 test = new cake2();
        test.cakes = 2; //inheritance
        test.CakeSize= 50; //not inheritance
        MessageBox.Show(test.cakes.ToString() + " | " + test.CakeSize.ToString());
    }
}
public class cake
{
    private int _cakes;
    public int cakes // get value
    {
        get
        {
            return _cakes;
        }
        set
        {
            _cakes = value;
        }
    }
    public cake()
    {
        public cake() : this(0) { } //constructor chaining.  Call your original function if no value is passed in
    }
    public cake(int number) // constructor
    {
        _cakes = number;
    }
    public static int cakes_plus_number(int n) // number plus constant //I don't see the need for static here, but whatever.
    {
        return n + 42;
    }
}
public class cake2 : cake
{
    private int _cake2;
    public int cakes2
    {
        get { return _cake2; }
        set { _cake2 = value; }
    }
    private int _size;
    public int CakeSize
    {
        get { return _size; }
        set { _size = value; }
    }
  }
}