了解c#中的基础
我正在尝试理解基础构造函数的实现。 考虑这种情况如果我有基类运动
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"); } }
现在我有inheritanceSport类的篮球课,我想在篮球对象初始化中使用带有两个参数的第二个构造函数。
public class Basketball : Sport { public Basketball : base ( ???? ) { ????? } }
首先,我想使用私有字段int _Id和string _Name,并在构造函数调用中使用它们
public Basketball : base ( int _Id, string _Name ) { Id = _Id; Name = _Name; }
但这对使用inheritance没有意义,所以请在这个例子中解释我。
更新谢谢大家,我正在使用这样的代码,没关系。
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)上使用as params )打我的基础构造。
谢谢大家。非常有帮助/
如果基类构造函数没有任何default parameterless constructor
函数,则必须将derives class
values
或variables
传递给base class constructor
default parameterless constructor
。
您不需要在基础构造函数调用中声明任何内容
base关键字的主要目的是调用base class constructor
。
通常,如果您没有声明自己的任何构造函数,编译器会为您创建一个default constructor
。
但是,如果您定义自己的具有parameter
的构造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
这完全取决于您在实例化derived
类时希望类的行为方式
您要求的构造函数如下:
public Basketball(int id, string name) : base(id,name) {}
构造函数不是inheritance的 – 这就是为什么你必须调用基础构造函数来重用它。 如果您不想做除基本构造函数之外的任何其他操作:
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; }
你需要在Basketball的构造函数中获得相同的参数:
public Basketball(int id, string name) : base(id, name)
或者以某种方式获取构造函数中的值,然后通过属性设置它们:
public Basketball() { int id = ...; string name = ...; base.Id = id; base.Name = name; }
关键字base
允许您指定要传递给基础构造器的参数。 例如:
public Basketball(int _Id, string _Name) : base (_Id, _Name ) { }
将使用2个参数调用基础构造函数,并且:
public Basketball(int _Id, string _Name) : base () { }
将调用您的基础构造函数没有参数。 这真的取决于你想要打电话给哪一个。