简体   繁体   中英

Inheritance/classes in C#

I am new to C#, and are trying to understand classes and "is a" relationships. I've been trying to get a piece of code to work, but I can't seem to get it right.

It looks like this: http://pastebin.com/cQDusptB

I have a base class, Mammal, which one should be able to create instances of, giving the name of the mammal as input. I also have a class, Dog, which is a Mammal. One should be able to create an instance of this too, in the same manner as Mammal.

Can anyone see my flaw(s)? If yes, can you please explain what i misunderstood/forgot?

When posting questions like this it is helpful to also post the error message the compiler gave you.

Can anyone see my flaw(s)?

You have a virtual constructor.

can you please explain what i misunderstood/forgot?

Constructors are not inherited in C# and therefore it makes no sense to mark them as either virtual or override .

The constructor of Dog needs to be named "Dog". You can't/don't need to override "Mammal". Also, Mammal's constructor shouldn't be virtual.

public class Mammal 
{

    public Mammal(string name)
    {
        //....
    }
}

public class Dog : Mammal {

    public Dog(string name) : base(name) 
    {
    }
}

You pass arguments to the base class constructor using the "base" keyword (see code above).

Be sure to pick up a good book on C# to get the language basics right.

You have a few issues here. For one, constructors can not be marked as virtual or overridden. Another problem is that you attempt to call the method .Name without parentheses. The corrected version looks like this:

public class Mammal
{
    protected string _Name;

    public virtual string Name()
    {
            return (this._Name + " - of type " + this.GetType());
    }
    public Mammal(string Name)
    {
        this._Name = Name;
    }
}
public class Dog : Mammal
{
    public Dog(string Name) : base(Name)
    {
    }

    public override string Name()
    {
        return (base._Name + "Dog");
    }
}

static void Main()
{
    Mammal AnimalA = new Mammal("SubjectA");
    Console.WriteLine("{0}", AnimalA.Name());

    Mammal AnimalB = new Dog("SubjectB");
    Console.WriteLine("{0}", AnimalB.Name());
    Console.ReadLine();
}

Constructors are not inherited/overridden.

  • Lose the 'virtual' keyword from the Mammal constructor in the Mammal class.
  • Remove the Mammal ctor override attempt in the Dog class.
  • Replace it with a Dog constructor that calls the Mammal one (like this):

public Dog(string name) : base(name) {

}

Now when a dog is constructed it will call through to the mammal base class constructor passing the specified name.

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