【发布时间】:2021-11-30 13:02:33
【问题描述】:
我想知道是否可以通过调用控制台应用程序或超超类来覆盖方法?我知道我可以在 DoMath 覆盖 WriteLog.... 但是考虑到我想在控制台应用程序中管理它。
例子:
public class LogThings
{
public virtual void WriteLog(string value)
{
Console.WriteLine("This is the base in LogThings " + value);
}
}
继承基类的类。我想如果我再次添加该方法并将其标记为 new 以实现为虚拟,那么我可以在继承 DoMath 的控制台应用程序中覆盖它?
public class DoMath : LogThings
{
public double DoAddition(double a, double b)
{
double result;
result = a + b;
WriteLog(result.ToString()); // < the operation I need to overload
return result;
}
public new virtual void WriteLog(string value)
{
Console.WriteLine("this is overriding the base in DoMath");
base.WriteLog(value);
}
}
一些使用 doMathANDLog 类库的控制台应用程序:
class Program : DoMath
{
static void Main(string[] args)
{
var m = new DoMath();
m.DoAddition(1, 2);
Console.ReadLine();
}
public override void WriteLog(string value)
{
Console.WriteLine("this is not overriding.");
}
}
运行结果是这样的:
这是覆盖 DoMath 中的基础
这是 LogThings 3 中的基础
有没有办法做到这一点?
【问题讨论】:
-
您为什么声称
DoMath中的方法在未覆盖基本方法时会覆盖它,而是创建一个新方法?如果你想覆盖它实际上是override它。 -
您正在创建
DoMath的实例,而不是Program的实例。但即使您要创建 Program 的实例,DoMath 也会重新定义方法 WriteLog 而不是覆盖它。 -
我想如果我再次添加该方法并将其标记为 new 以实现为虚拟 - 再次由我运行?
-
非常困惑您想要什么以及您如何努力实现这一目标...stackoverflow.com/questions/392721/… 可能适合您阅读edit 问题以阐明您想要实现的目标以及您需要成为什么解释。
标签: c# inheritance polymorphism