简体   繁体   中英

error in calling base constructor c#

class Student
{
    int id;
    string name;
    public Student(int id, string name)
    {
        this.id = id;
        this.name = name;
    }
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
class SubStudent : Student
{
    int ssn;
    public SubStudent(int id, int name, int ssn)
        : base(int id, string name)
    {

    }
}

The above code generates an error "invalid expression for term int" What could be wrong?

public SubStudent(int id, string name, int ssn)
    : base(int id, string name)

should be

public SubStudent(int id, string name, int ssn)
    : base(id, name)

You are not declaring the base constructor's signature again, you are just calling it. And as in any other call, the types of the parameters are not specified at the call site.

Edit: corrected int name to string name in the parameter list of the SubStudent ctor.

You don't need to repeat the type names in the call to base. It should be:-

class SubStudent : Student
{    
    int ssn;    
    public SubStudent(int id, string name, int ssn)
        : base(id, name)
    {
    }
}

As Jon says, it's the way you're calling the base constructor.

The idea is you're providing arguments to the base constructor, not declaring parameters . So you use the same syntax as if you were calling a method:

base(id, name)

Note that the arguments don't have to come from your own constructor parameters. This would be valid, for example:

public SubStudent(int id, int name, int ssn) : base(10, "fixed name")

In this case it's unlikely to be desirable, but it would be valid :)

You shouldn't put types in the base constructor call:

public SubStudent(int id, int name, int ssn)
        : base(id, name)
    {

    }
class SubStudent : Student 
{     
    int ssn;     
    public SubStudent(int id, int name, int ssn)         
       : base(id, name)     
    {      
    } 
} 

Try above code.

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