【发布时间】:2011-03-23 03:21:16
【问题描述】:
我是 C# 新手,正在尝试理解基本概念。预先感谢您的帮助。我在下面有一些示例类(在此窗口中输入,因此可能存在一些错误)并且有两个问题:
-
是否可以调用派生类方法执行同名基类方法中的代码,然后执行派生类方法中的代码?每个派生类都需要执行 RunCheck 的基类代码,然后执行特定于其类的专门代码。我可以在基类中将 RunCheck() 命名为其他名称,然后在调用派生类的 RunCheck() 时调用它,但我必须记住在派生类的 RunCheck() 上调用它。
-
在 Program.cs 中,如果它位于我传入的派生类之外的字段上,我想输出所有具有空白值的字段。我会传入什么?
李>
这是我的代码:
class baseCheck
{
public DateTime StartTime { get; set; }
public DateTime LastRun { get; set; }
public int Runs { get; set; }
//Others
public void RunCheck()
{
if (Started != null)
started = DateTime.Now;
LastRun = DateTime.Now;
Runs++;
}
}
class FileCheck : baseCheck
{
public string FileName { get; set; }
public void RunCheck()
{
//I want all the code in the base class to run plus
//any code I put here when calling this class method
}
}
class DirectoryCheck : baseCheck
{
public string DirectoryName { get; set; }
public void RunCheck()
{
//I want all the code in the base class to run plus
//any code I put here when calling this class method
}
}
//Program.cs
static void Main()
{
//Create derived class - either DirectoryCheck or FileCheck
//depending on what the user chooses.
if (Console.ReadLine()=="F")
{
FileCheck c = new FileCheck();
}
else
{
DirectoryCheck c = new DirectoryCheck();
}
PrintOutput(c);
}
private void PrintOut(What do I put here?)
{
Console.WriteLine("Started: {0}",f.StartTime)
Console.WriteLine("Directory: {0}", f.DirectoryName)
Console.WriteLine("File: {0}", f.FileName}
}
【问题讨论】:
-
在您的派生方法中,调用“super.RunCheck()”。它将调用父类方法。
标签: c# .net inheritance extension-methods