我发现了一堆与此相关的问题,但没有完全回答,尽管我确定它在某处。如何找到没有多个“is”语句的派生类的类型?
我正在寻找简单地找到我正在从基类引用处理哪个派生类。
我的代码块这样
public void AddMenu(iTarget target, Menu callingMenu)
{
if (target is Corporation)
AddMenu(target as Corporation, callingMenu);
if (target is Company)
AddMenu(target as Company, callingMenu);
if (target is Asset)
AddMenu(target as Asset, callingMenu);
if (target is Operative)
AddMenu(target as Operative, callingMenu);
}
而且
if (uip.UIPButton is UIPCorporationButton)
btn = UIPCorporationButton.Create(contents.gameObject, (uip as Corporation));
else if (uip.UIPButton is UIPCompanyButton)
btn = UIPCompanyButton.Create(contents.gameObject, (uip as Company));
else if (uip.UIPButton is UIPAssetButton)
btn = UIPAssetButton.Create(contents.gameObject, (uip as Asset));
else if (uip.UIPButton is UIPIndButton)
//so on and so on
而且我喜欢用这样的:
public void AddMenu(iTarget target, Menu callingMenu)
{
AddMenu(BaseClass(target));//or whatever would send iTarget as Corporation, Company, or whatever it's base type is
}
或者类似的东西:
public void DoThing(iTarget target)
{
switch(target.BaseClass)//or whatever
{
case Corporation:
//stuff
break;
case Company:
//other stuff
break;
}
}
有没有一种方法来获取派生类并将其用作上面的参考?
您正在寻找访客模式。 – SLaks