我正在使用一个为我生成一堆类的库。
这些类都继承自一个公共(public)基类,但该基类没有定义所有子类共有的几个方法。
例如:
SubClassA : BaseClass{
void Add(ItemA item) {...}
ItemA CreateNewItem() {...}
}
SubClassB: BaseClass{
void Add(ItemB item) {...}
ItemB CreateNewItem() {...}
}
不幸的是,基类没有这些方法。这会很棒:
BaseClass{
// these aren't actually here, I'm just showing what's missing:
abstract void Add(ItemBaseClass item); // not present!
abstract ItemBaseClass CreateNewItem(); // not present!
}
由于我的 A+B 对象有一个公共(public)基类,Item 对象有一个公共(public)基类,我曾希望从多态性的美妙世界中受益。
不幸的是,由于公共(public)方法实际上并不存在于基类中,所以我无法虚拟地调用它们。例如,这将是完美的:
BaseClass Obj;
Obj = GetWorkUnit(); // could be SubClassA or SubClassB
ItemBaseClass Item = Obj.CreateNewItem(); // Compile Fail: CreateNewItem() isn't in the base class
Item.DoSomething();
Obj.Add(Item); // Compile Fail: Add(...) isn't in the base class
显然转换会起作用,但我需要知道我有哪种类型会抵消好处。
如何“强制”调用这些方法?我不担心得到一个没有实现我试图调用的方法的对象。我实际上可以在 VB 中做我想做的事——我没有智能感知,但编译器很高兴并且它可以工作:
CType(Obj, Object).Add(Item) // Note: I'm using C#--NOT VB
再次声明,我无法控制这些类(我认为这排除了部分类)。
最佳答案
如果不借助反射或其他肮脏的技巧,就不能调用派生类的非虚拟方法。如果您想这样做,那很容易:
// obj is your object reference.
obj.GetType().InvokeMember("MethodName",
System.Reflection.BindingFlags.InvokeMethod, null, obj, null /* args */)
关于c# - 如何在基类对象上调用子类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/757371/