Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Can I dynamically instantiate an interface at runtime? Well Yes I can but is there a better way?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, I would use a Dictionary with Activator.CreateInstance:

Dictionary<buildingType, Type> typeMap = new Dictionary<buildingType, Type>()
{
   { buildingType.House, typeof(House) }
}

IBuilding building = (IBuilding)Activator.CreateInstance(typeMap[userSelection]);

If this were WPF, you could use a converter to do this directly from the view to the view model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...