- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
好的,下面是练习:您必须定义三个类。一个名为 MyNum 的类包含一个 int 类型的变量。第二类称为 MyString,将从 MyNum 派生并包含字符串。第三类调用MyType 并返回一个MyNum 类型的变量。每个类都会设置一个名为Show 的构造函数和虚函数。 MyType 的构造函数接收一个 MyNum 变量,而 MyType 的 Show 函数将运行 MyNum 的 Show 函数。现在,您需要设置两个 MyType 类型的对象并初始化它们。一次是 MyNum 类型的对象,一次是 MyString 类型的对象。
代码如下:
class MyNum
{
protected int num;
public MyNum(int num)
{
this.num = num;
}
public virtual void Show()
{
Console.WriteLine("The number is : " + num);
}
}
class MyString : MyNum
{
string str;
public MyString(string str)
{
this.str= str;
}
}
class MyType : MyNum
{
MyNum num2;
public MyType(MyNum num)
{
this.num2 = num;
}
public override void Show()
{
base.Show();
}
}
class Program
{
static void Main(string[] args)
{
}
}
我有以下错误:
错误 1“ConsoleApplication1.MyNum”不包含采用“0”参数的构造函数 C:\Users\x\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 23 16 ConsoleApplication1
有人知道我为什么会遇到这个错误吗?谢谢。
最佳答案
由于您的类是 MyNum
的子类,因此它需要能够构造它。您没有默认构造函数,因此必须使用值显式调用它。
例如:
// Since this is here, you're saying "MyType is a MyNum"
class MyType : MyNum
{
MyNum num2;
public MyType(MyNum num) // You need to call the base class constructor
// here to construct that portion of yourself
: base(42) // Call this with an int...
{
this.num2 = num;
}
MyString
类需要类似的处理。它也必须有一个调用基类构造函数的构造函数。
请注意,如果 MyNum
类有默认构造函数(可能是 protected
),则这无关紧要。除了调用这些构造函数之外,另一种方法是执行以下操作:
class MyNum
{
public MyNum(int num)
{
this.num = num;
}
// Add a default constructor that gets used by the subclasses:
protected MyNum()
: this(42)
{
}
根据评论进行编辑:
如果你想覆盖基类的构造函数,试试:
class MyType : MyNum
{
public MyType(int num)
: base(num)
{
}
public override void Show()
{
Console.WriteLine("The number [MyType] is : " + this.num);
}
}
关于c# - 非常基本的虚函数练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6528330/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!