[英]Call a method in every derived class
它是一种在每个派生类中调用方法的方法吗?
我需要它与用户脚本一起使用,所以我不能强迫用户调用base.Update();
无论他是否进行了基本呼叫,我都需要它。
public class Base
{
public virtual void Update()
{
Console.WriteLine("BASE UPDATE");
;
}
}
public class Base2 : Base
{
public override void Update()
{
Console.WriteLine("BASE2 UPDATE");
;
}
}
public class Base3 : Base2
{
public override void Update()
{
// base.Update() ? no no, i want to do it for User Scripts so i cant force user to call base.Update()
Console.WriteLine("BASE3 UPDATE");
}
}
public class TestClass
{
public void DoTheTest()
{
Base3 instance = new Base3();
instance.Update();
// the output i need:
/*
BASE UPDATE
BASE2 UPDATE
BASE3 UPDATE
*/
}
}
不是优雅的方式,但它的工作原理
public interface IUpdateHandler
{
void UpdateHandler();
}
public class Base : IUpdateHandler
{
public Base()
{
OnUpdate += (s, e) => UpdateHandler();
}
public void Update()
{
OnUpdate(this, null);
}
public void UpdateHandler()
{
Console.WriteLine("BASE UPDATE");
}
protected event EventHandler OnUpdate;
}
public class Base2 : Base, IUpdateHandler
{
public Base2()
{
OnUpdate += (sender, args) => UpdateHandler();
}
public new void UpdateHandler()
{
Console.WriteLine("BASE2 UPDATE");
}
}
public class Base3 : Base2, IUpdateHandler
{
public Base3()
{
OnUpdate += (sender, args) => UpdateHandler();
}
public new void UpdateHandler()
{
Console.WriteLine("BASE3 UPDATE");
}
}
所以你有一个Base类的对象,或Base的派生类的对象,你想从上到下(base1 / base2 / base3)以层次结构的顺序调用所有可用的Update()函数
从任何对象,您都可以获得Type对象。 您也可以要求基类类型。 从每个Type对象,您可以询问它是否知道具有特定名称的方法。 如果是,您可以调用此方法。
。
public void UpdateHierarchical(Base someObject)
{
UpdateHierarchical(someObject.GetType(), someObject);
}
private void UpdateHierarchical(Type type, object obj)
// if the object has a base class
// call this function recursively with type = base type
// if this type has has an Update, call it,
Type type = obj.GetType(); // the type of obj
Type baseType = type.BaseType(); // the base type of obj
if (baseType != null) // there is a base type
UpdateHierarchical(baseType, obj);
// now that all base Update() are called,
// check if this type has an Update
MethodInfo updateInfo = type.GetMethod("Update")
if (updateInfo != null)
{ // this type has an Update()
updateInfo.Invoice(obj, null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.