我正在尝试理解基础构造函数的实现。考虑这种情况 如果我有基础运动
public class Sport
{
public int Id { get; set; }
public string Name { get; set; }
public Sport()
{
Console.WriteLine("Sport object is just created");
}
public Sport(int id, string name)
{
Console.WriteLine("Sport object with two params created");
}
}
现在我有继承Sport类的篮球课,我想在篮球对象初始化中使用带有两个参数的第二个构造函数。
public class Basketball : Sport
{
public Basketball : base ( ???? )
{
?????
}
}
首先我想使用私有字段int _Id和string _Name并在构造函数调用中使用它们
public Basketball : base ( int _Id, string _Name )
{
Id = _Id;
Name = _Name;
}
但这对使用继承没有意义,所以请在这个例子中解释我。
更新 谢谢大家,我正在使用这样的代码,没关系。
public Basketball(int id, string name) : base (id, name)
{
Id = id;
Name = name;
}
只是为了确保,在这一行public Basketball(int id, string name) : base (id, name)
我声明变量id,name,因为我的原始是大写的变量,并使用base(id,name)作为params来命中我的基本构造函数。 / p>
谢谢大家。非常有帮助/
答案 0 :(得分:4)
您要求的构造函数如下:
public Basketball(int id, string name) : base(id,name) {}
答案 1 :(得分:3)
如果基类构造函数没有任何values
,则必须将variables
的{{1}}或derives class
传递给base class constructor
。
您不需要在基础构造函数调用中声明任何内容
base关键字的主要目的是调用default parameterless constructor
。
通常,如果您没有声明自己的任何构造函数,编译器会为您创建base class constructor
。
但是如果您定义自己的构造函数default constructor
,那么编译器不会创建parameter
。
因此,如果您没有在基类中声明的默认构造函数并且想要调用具有参数的基类构造函数,则必须调用该基类构造函数并通过default parameterless constructor
关键字传递所需的值
这样做
base
或强>
public Basketball() : base (1,"user")
或强>
public Basketball(int id,string n) : base (id,n)
或强>
public Basketball(int id,string n) : base ()
类似于
public Basketball() : base ()
这完全取决于您在实例化public Basketball()//calls base class parameterless constructor by default
类时希望您的课程如何表现
答案 2 :(得分:2)
构造函数不是继承的 - 这就是为什么你必须调用基础构造函数来重用它。如果您不想做除基本构造函数之外的任何其他操作:
public Basketball( int id, string name ) : base ( id, name )
{
}
您的示例有点误导,但是因为您没有在基础构造函数中使用id
和name
参数。一个更准确的例子是:
public Sport(int id, string name)
{
Console.WriteLine("Sport object with two params created");
Id = id;
Name = name;
}
答案 3 :(得分:1)
你需要在Basketball的构造函数中获得相同的参数:
public Basketball(int id, string name) : base(id, name)
或以某种方式获取构造函数中的值,然后通过属性设置它们:
public Basketball()
{
int id = ...;
string name = ...;
base.Id = id;
base.Name = name;
}
答案 4 :(得分:0)
关键字base
允许您指定要传递给基础构造器的参数。例如:
public Basketball(int _Id, string _Name) : base (_Id, _Name )
{
}
将使用2个参数调用基础构造函数,并且:
public Basketball(int _Id, string _Name) : base ()
{
}
将调用没有参数的基础构造函数。这真的取决于你想要打电话给谁。