2 回答
TA贡献1898条经验 获得超8个赞
最接近伪代码的方法是将一个Action委托字段添加到基类中,如下所示:
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
AChildClass instance = new AChildClass()
{
DoSomethingExtra = () => Console.WriteLine("print this also")
};
instance.DoAThing();
}
}
public class ABaseClass
{
public Action DoSomethingExtra;
public virtual void DoAThing()
{
DoSomethingExtra();
Console.WriteLine("print this base");
}
}
public class AChildClass : ABaseClass
{
public override void DoAThing()
{
Console.WriteLine("child override");
base.DoAThing();
}
}
输出:
child override
print this also
print this base
由于它是一个字段,因此您可以在实例化后随时更改委托指向的方法:
instance.DoSomethingExtra = () => Console.WriteLine("new thing");
TA贡献1802条经验 获得超5个赞
除非您动态重新编译,否则您不能覆盖用C#编译后的方法。
如评论中所述,一种可能的方法是使用委托。您可以将委托传递到可选的构造函数中DoAThing,并在传入的情况下调用它:
public class AChildClass : ABaseClass
{
private readonly Action _doAThing;
public AChildClass() { }
public AChildClass(Action doAThing)
{
_doAThing = doAThing;
}
public override void DoAThing()
{
if (_doAThing != null)
{
_doAThing();
}
print("child override");
base.DoAThing();
}
}
在您的情况下,该实例化为:
AChildClass instance = new AChildClass(() =>
{
// Do some extra stuff
print("print this also");
// do child class stuff and base stuff
print("child override")
});
调用时将触发另外两个打印语句:
instance.DoAThing();
也打印此
- 2 回答
- 0 关注
- 119 浏览
添加回答
举报