C# c语言中的理解库#

C# c语言中的理解库#,c#,oop,C#,Oop,我试图理解基本构造函数的实现。考虑这种情况 如果我有基本的运动 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)

我试图理解基本构造函数的实现。考虑这种情况 如果我有基本的运动

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");
   }
}
现在我在Herhit Sport类中有了basketball类,我想在basketball对象初始化上使用第二个构造函数和两个参数

public class Basketball : Sport
{    
    public Basketball : base ( ???? )
    {
       ?????
    }
}
首先,我想使用私有字段int\u Id和string\u 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,因为我的原始变量是大写的vars,并将其用作base(id,name)上的参数以命中我的base构造函数


谢谢大家。非常有帮助。

您要求的构造函数如下:

public Basketball(int id, string name) : base(id,name) {}

构造函数不是继承的-这就是为什么必须调用基构造函数来重用它。如果您不想做任何与基本构造函数不同的事情,只需使用:

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;
}

如果基类构造函数没有任何默认的无参数构造函数,则必须将
派生类的
变量
传递给
基类构造函数

您不需要在基构造函数调用中声明任何内容

base关键字的主要用途是调用
基类构造函数

通常,如果您没有声明自己的构造函数,编译器会为您创建一个
默认构造函数

但是如果您定义自己的构造函数具有
参数
,则编译器不会创建
默认无参数构造函数

因此,如果在基类中没有声明默认构造函数,并且希望调用具有参数的基类构造函数,则必须调用该基类构造函数,并通过
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(int id,string n) : base (id,n)
public Basketball(int id,string n) : base ()
public Basketball() : base ()

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

这完全取决于当实例化
派生的
类时,您希望类的行为方式关键字
base
允许您指定要传递给基本构造函数的参数。例如:

public Basketball(int _Id, string _Name) : base (_Id, _Name )
{
}
将使用2个参数调用基本构造函数,并且:

public Basketball(int _Id, string _Name) : base ()
{
}

将调用没有参数的基构造函数。这实际上取决于您要调用哪一个。

您需要在Basketball的构造函数中获取相同的参数:

public Basketball(int id, string name) : base(id, name)
或者以某种方式获取构造函数中的值,然后通过属性设置它们:

public Basketball()
{
    int id = ...;
    string name = ...;

    base.Id = id;
    base.Name = name;
}

@DStanley
Base
可用于调用基类的受保护和公共变量及方法。然而,这个答案并不真正相关,也没有回答这个问题。@Msonic很公平-我想这让我很困惑,因为我不记得曾经见过被覆盖的属性。@Msonic我认为这是相关的。有时,在子类构造函数中的某些代码执行之前,不可能获取基构造函数的所有参数。您应该解释为什么它是这样工作的,因为OP不理解base关键字。