How to create a new object instance from a Type

后端 未结 12 1960
孤城傲影
孤城傲影 2020-11-22 03:26

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.

How do you get a new objec

12条回答
  •  感动是毒
    2020-11-22 03:51

    Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

    public object GetInstance(string strNamesapace)
    {         
         Type t = Type.GetType(strNamesapace); 
         return  Activator.CreateInstance(t);         
    }
    

    If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

    public object GetInstance(string strFullyQualifiedName)
    {
         Type type = Type.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
         foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
         {
             type = asm.GetType(strFullyQualifiedName);
             if (type != null)
                 return Activator.CreateInstance(type);
         }
         return null;
     }
    

    And you can get the instance by calling the above method.

    object objClassInstance = GetInstance("Vehicles.Car");
    

提交回复
热议问题