2
votes

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: enter image description here

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

2
I strongly suggest using a Bitmap attribute and not override the PictureBox - kevintjuh93
A weapon is not a substitute for a PictureBox. I think you should probably rethink your design. - Darren Young
Picturebox has all the properties I need. I only have a day to create this so the overall design is not important as long as it works. I will take a look at the Bitmap attibute though. Thanks - pvdev
I assume you're just working with picture boxes here, so it's really an ItemPictureBox, WeaponPictureBox etc. - Jeb

2 Answers

2
votes

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.

e.g.:

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

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.