What is the best way to instantiate a pedigree name?

Assuming I only have the generic class name as a string in the form “MyCustomGenericCollection (of MyCustomObjectClass)” and don’t know the assembly from which it comes, what is the easiest way to instantiate this object?

If this helps, I know that the class implements IMyCustomInterface and is from the assembly loaded into the current AppDomain.

Marcus Olsson gave a great example here , but I don’t see how to apply it to generics.

+3
source share
3 answers

After you parse it, use Type.GetType (string) to get a reference to the corresponding types, then use Type.MakeGenericType (Type []) to create the specific specific type that you need. Then use Type.GetConstructor (Type []) to get a constructor reference for a specific generic type, and finally call ConstructorInfo.Invoke to get an instance of the object.

Type t1 = Type.GetType("MyCustomGenericCollection"); Type t2 = Type.GetType("MyCustomObjectClass"); Type t3 = t1.MakeGenericType(new Type[] { t2 }); ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes); object obj = ci.Invoke(null); 
+7
source

MSDN Article How-To. Learning and activating generic types with Reflection describes how you can use Reflection to instantiate a generic type. Using this in conjunction with the Marksus sample, we hope you get started.

+2
source

If you don't mind translating to VB.NET, something like this should work

 foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // find the type of the item Type itemType = assembly.GetType("MyCustomObjectClass", false); // if we didnt find it, go to the next assembly if (itemType == null) { continue; } // Now create a generic type for the collection Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);; IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType); break; } 
+1
source

All Articles