简体   繁体   中英

Base class inheriting from another base class?

I'm trying to create some classes for a small windows game in C#. I have a class Weapon with a constructor, which inherits from my base class 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;
    }
}

Item class:

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

}

This all works fine, I can call my constructor and create instances of Weapon object. However, I also want my Item and Weapon classes to inherit from the PictureBox class, like this:

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

}

However applying the code above leads to an error "Constructor on type 'MyNamespace.Item' not found"

Am I approaching this the correct way? How can I get my Item base class to inherit from another base class?

EDIT: the error comes from within VS when opening the class file: 在此处输入图片说明

Why is it trying to open my class file in the form designer? I don't understand!

I believe it is correct as long as the base class is not marked as sealed and has an appropriate constructor. When you create the Item class, the constructor will now need to call the base PictureBox constructor, and use one of its public constructors.

eg:

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

You need a parameterless constructor; otherwise, the designer cannot display your control (since you derive it from PictureBox , it is a control now, so opening the file by double click will load the designer).

According to the component-based approach, the components must be able to be restored by creating them by a default constructor and by setting the public properties, which you can set in a property grid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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