Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

inheritance - C# Error: Parent does not contain a constructor that takes 0 arguments

My code is

public class Parent
{

    public Parent(int i)
    {
        Console.WriteLine("parent");
    }
}

public class Child : Parent
{
    public Child(int i)
    {
        Console.WriteLine("child");
    }

}

I am getting the error:

Parent does not contain a constructor that takes 0 arguments.

I understand the problem is that Parent has no constructor with 0 arguments. But my question is, why do we need a constructor with zero arguments? Why doesn't the code work without it?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

Or, you can just add a parameterless parent constructor:

protected Parent() { } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...