我是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()'。它会调用父类的方法。 – Doodloo 2011-03-23 03:24:24