我是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} }
解决方法
只需在DirectoryCheck类中调用base.RunCheck():
public 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 base.RunCheck(); Console.WriteLine("From DirectoryCheck"); } }
还有你当前的实现,你隐藏基类RunCheck()方法 – 你应该重写它 – 这会将基类中的方法签名更改为
public virtual void RunCheck()
并在派生类中
public override void RunCheck()
我怀疑你真正想要的是像Non Virtual interface模式(NVI) – 在基类中暴露一个受保护的虚拟方法,子类可以覆盖,但是在基类上实际上是调用该方法的公共方法 – 这种方法允许您扩展您在该呼叫之前和之后所做的工作.
在你的例子中,它将如下所示:
class BaseCheck { private DateTime Started { get; set; } 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++; CoreRun(); } protected virtual void CoreRun() { } } public class DirectoryCheck : BaseCheck { public string DirectoryName { get; set; } protected override void CoreRun() { //I want all the code in the base class to run plus //any code I put here when calling this class method Console.WriteLine("From DirectoryCheck"); } }