>是否可以调用派生类方法,该方法使用相同的名称在基类方法中执行代码,然后在派生类方法中执行代码?每个派生类都需要为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"); }}总结
以上是内存溢出为你收集整理的c# – 扩展基类方法全部内容,希望文章能够帮你解决c# – 扩展基类方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)