Create an object knowing only the class name?

后端 未结 5 1287
花落未央
花落未央 2020-12-15 22:16

I have a set of classes, each one is a different strategy to do the same work.

namespace BigCorp.SuperApp
{
    public class BaseClass { }
    public class          


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 22:48

    I'm going with the full type name in the application configuration. Below is a slightly more complete, but still trivial example

    
       
          
          
       
    
    

    And the factory class that actually creates this

    private static Assembly a = typeof(IFactoryObject).Assembly;
    public static IFactoryObject CreateObject(String providerName)
    {
        Type t = a.GetType(providerName)
        IFactoryObject o = Activator.CreateInstance(t) as IFactoryObject;
        return o;
    }
    

提交回复
热议问题