简体   繁体   English

调用基础构造函数c#时出错

[英]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? 上面的代码生成错误“term int的无效表达式”可能有什么问题?

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. 编辑:SubStudent ctor的参数列表中更正了int namestring name

You don't need to repeat the type names in the call to base. 您不需要在对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. 正如Jon所说,这就是你调用基础构造函数的方式。

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. 试试上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM