开发者

Inheritance issue C#

I've got a small problem with inheritance in my application. I've got a base class Client, w开发者_JS百科hich has a subclass Job. Basically, I'm trying to create a constructor for Job but I'm getting an error saying "'Job_Manager_Application.Client' does not contain a constructor that takes 0 arguments"

Can't figure out why it's doing this?

Thanks in advance.


Your Client class has a constructor that takes parameters.

Therefore your Job constructor needs to pass parameters to Client.

Example:

class Client{
    public string Name {get;set;}
    public Client(string name){
        this.Name = name;
    }
}

--

class Job:Client{
    public double Rate {get;set;}

    public Job(double rate){
        // This won't compile, because Client won't have its "name" parameter.
    } 

    public Job(string name, double rate) : base(name){
        // So you need to pass a parameter from your Job constructor using "base" keyword.
        this.Rate = rate;
    }

    public Job(double rate) : base("Default Name"){
        // You could do this, this is legal.
    } 
}


Why is Job a subclass of a Client? Inheritance represents is a relationships (a Cat is a Animal so class Cat : Animal { }). A Job is not a Client.

Anyway, your error message is clear. You don't have an accessible parameterless constructor on Client. You need to explicitly invoke a constructor on client from a constructor on Job then.

class Client {
    public string Name { get; set; }
    public Client(string name) { this.Name = name; }
}

class Job : Client {
    public Job(string name) : base(name) { }
}

See that base(name) there? That is invoking the base constructor Client.Client(string) on Client. If you don't specify a base constructor explicitly, the compiler tries to find an accessible parameterless constructor. If there is not one, you get the compile time error that you experienced.

So, you either need to do as I've done above, which is invoke an accessible non-parameterless constructor explicitly, or add a parameterless constructor to Client.

But please, rethink your model. A Job is not a Client.


Client has a constructor that takes arguments and you aren't calling it properly

public class Job
{
    public Job(int num) { }
}

public class Client : Job
{
    public Client() : base(1) {}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜