我需要创建一个Event的继承性作为一个SwimmingEvent但是我收到的错误是构造函数不包含0个参数,问题是我不知道哪些参数是要传递的。任何帮助将不胜感激。
//Base Class
class Event
{
private string m_evName;
private string m_evDate;
private string m_evTime;
private string m_evFee;
private string m_evVenue;
private List<Athlete> m_athletes;
public String EvName { get { return m_evName; } }
public String EvDate { get { return m_evDate; } }
public String EvTime { get { return m_evTime; } }
public String EvFee { get { return m_evFee; } }
public String Venue { get { return m_evVenue; } }
//Getters/Setters - Making private variables avilable in public space through class method
public Event(String EvName, String EvDate, String EvTime, String EvFee, String EvVenue)
{
m_evName = EvName;
m_evDate = EvDate;
m_evTime = EvTime;
m_evFee = EvFee;
m_evVenue = EvVenue;
m_athletes = new List<Athlete>();
}
}
//child class
class SwimmingEvent : Event
{
private String m_distance;
private String m_inOutVar;
public SwimmingEvent(String Distance, String InOrOut)
{
m_distance = Distance;
m_inOutVar = InOrOut;
}
}
答案 0 :(得分:5)
由于SwimmingEvent
是 Event
,您需要将传递给Event
的构造函数的所有参数传递给{{1}的构造函数,然后一些:
SwimmingEvent
答案 1 :(得分:2)
using System;
public class MyBase
{
int num;
public MyBase(int i )
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived: MyBase
{
// This constructor will call MyBase.MyBase(int i)
***//You are missing this.***
public MyDerived(int i) : base(i)
{
}
}
答案 2 :(得分:1)
您需要将所有参数传递回您的父级。
class SwimmingEvent : Event
{
private String m_distance;
private String m_inOutVar;
public SwimmingEvent(String Distance, String InOrOut, string evName) : base (evName,"b","c", "d", "e")
{
m_distance = Distance;
m_inOutVar = InOrOut;
}
}
答案 3 :(得分:1)
可能是这样的:
public class Event
{
public Event() {} // public empty ctor
....
....
}
和派生
public class SwimmingEvent : Event
{
}
通过这种方式,您将避免(假设这是您想要的)编译时错误,因为具有空参数列表的ctor
已存在于基类中。
如果这不是您要搜索的内容,请澄清。
答案 4 :(得分:1)
class SwimmingEvent : Event
{
....
public SwimmingEvent(String Distance, String InOrOut)
:base(/*Arguments for base class constructor*/)
{
//Constructor of derived class
}
}
如果省略&#34;:base(...)&#34;,编译器假定调用基类的无参数构造函数,例如,如果你编写&#34;:base()&#34;。但是基类中没有无参数构造函数,因此您会收到错误。
您必须在Event类中创建无参数构造函数,或者添加&#34; base&#34;关键字并指定用于在SwimmingEvent声明中调用现有Event类的构造函数的参数。