繁体   English   中英

基类继承自另一个基类?

[英]Base class inheriting from another base class?

我正在尝试为C#中的小型Windows游戏创建一些类。 我有一个带有构造函数的Weapon类,该构造函数继承自我的基类Item

public class Weapon : Item
{
    public int Attack { get; set; }

    //constructor
    public Weapon(int id, string name, int value, int lvl, int attack) : 
        base(id, name, value, lvl)
    {
        Attack = attack;
    }
}

物品类别:

public class Item

{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Value { get; set; }
    public int Lvl { get; set; }

    //constructor
    public Item(int id, string name, int value, int lvl)
    {
        ID = id;
        Name = name;
        Value = value;
        Lvl = lvl;
    }

}

一切正常,我可以调用构造函数并创建Weapon对象的实例。 但是,我也希望我的Item和Weapon类从PictureBox类继承,如下所示:

public class Item : PictureBox 

{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Value { get; set; }
    public int Lvl { get; set; }

    //constructor
    public Item(int id, string name, int value, int lvl)
    {
        ID = id;
        Name = name;
        Value = value;
        Lvl = lvl;
    }

}

但是,应用上面的代码将导致错误“找不到类型'MyNamespace.Item'的构造函数”

我是否采用正确的方法? 如何获取我的Item基类以从另一个基类继承?

编辑:打开类文件时,错误来自VS: 在此处输入图片说明

为什么要尝试在表单设计器中打开我的类文件? 我不明白!

我相信这是正确的,只要基类未标记为已密封并且具有适当的构造函数即可。 创建Item类时,构造函数现在将需要调用基本PictureBox构造函数,并使用其公共构造函数之一。

例如:

//constructor
public Item(int id, string name, int value, int lvl)
: base(...params etc)
{

您需要一个无参数的构造函数; 否则,设计器将无法显示您的控件(因为您是从PictureBox派生的,它现在是一个控件,因此通过双击打开文件将加载设计器)。

根据基于组件的方法,必须能够通过默认构造函数创建组件并设置公共属性(可以在属性网格中设置)来恢复组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM