Say I have a bunch of classes that implement an interface:
public interface IBuilding
{
string WhatAmI();
}
Class house:IBuilding
{
string Ibuilding.WhatAmI(){return "A House";}
}
Class Skyscraper:IBuilding
{
string Ibuilding.WhatAmI(){return "A Skyscraper";}
}
Class Mall:IBuilding
{
string Ibuilding.WhatAmI(){return "A Mall";}
}
And then I want to dynamically choose what to instantiate the class:
enum buildingType { house, Skyscraper, Mall };
string someMethodOrAnother()
{
string building= textboxBuildingType.Text;
Ibuilding MyBuildingClass;
buildingType UserSelectedClass = (buildingType) Enum.Parse(typeof(buildingType), building);
if (Enum.IsDefined(typeof(buildingType), UserSelectedClass) )
{
MyBuildingClass = (some code that dynamically creates a class instance);
}
else
{
MyBuildingClass = new house();
}
return MyBuildingClass.WhatAmI;
}
Now I could do this in a switch statement, but I thought I had found a more elegant technique. Or is the whole idea of using an interface wrong? Perhaps I need a delegate instead?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…