【发布时间】:2017-07-05 16:31:13
【问题描述】:
你能给我解释一下吗? 我必须如何解决下面的简单任务?
class Base{}
class Derived1: Base { void Method(); }
class Derived2: Base { void Method();}
static void Main(string[] args)
{
Base object; //it is just a declaring
if (some condition is true)
object = new Derived1();
else
object = new Derived2();
//now i want to call one of methods of one of my derived classes
//object.MyMethod(); //of course wrong, object has no that method
//ok, i have to downcast it but i don't know which class to
//((object.GetType())object).Method(); //wrong
//is there only one way is to repeat conditions
//and to downcast explicitly?
if (some condition is true again)
(object as Derived1).Method();
else
(object as Derived2).Method();
}
当然,基类对 Method() 一无所知。
【问题讨论】:
-
如果有理由从基类派生,即 Derived1 和 Derived2 相关,则在基类上抽象或虚拟化您的方法;那么你就不需要投了。目前,您好像想说
if(x) then buy milk else tell the dog to bark。
标签: c# typeof downcast gettype