Reputation: 63
I find a bunch of questions close to this, but not quite answering it, though I'm sure it's on here somewhere.
I'm looking to simply find which derived class I'm dealing with from a base class reference.
I have blocks of code like this
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);
}
And
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
And I'd like to use something like this:
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
}
Or something like:
public void DoThing(iTarget target)
{
switch(target.BaseClass)//or whatever
{
case Corporation:
//stuff
break;
case Company:
//other stuff
break;
}
}
Is there a way to just get the derived class and use it as a reference like above?
Upvotes: 0
Views: 92
Reputation: 12459
GetType() with an if/else statement will do what you want.
private abstract class Base1
{
}
private class Extend1 : Base1
{
}
Base1 whatTypeAmI = new Extend1();
var t = whatTypeAmI.GetType();
if (t == typeof(Extend1))
{
//do work
Console.WriteLine("hello extend1");
}
else {
Console.WriteLine("I don't know what type I am");
}
}
Upvotes: 1
Reputation: 17328
Make sure you really need that switch statement first. I don't know how your AddMenu
works exactly, but if it takes an ITarget
, why do you need the cast at all? Just call it with the base class.
Often, if this "switch on a type" construct is seemingly required, there is a design flaw. A virtual method call is the ordinary way to do this, so consider refactoring your code so you can do
target.AddMenu(callingMenu);
instead.
Upvotes: 3