Assembly assembly = Assembly.GetCallingAssembly();
assembly.CreateInstance("MyType");
and
Activator.CreateInstance(typeof(MyType));
Ok, the Activator.CreateInstance can be generic which eliminates the need to cast yo开发者_如何学运维ur created instance, but when would you use one against the other?
The string-based version looks only in the root namespace (since no namespace is included) of the current assembly (since no assembly name is included), plus a few system assemblies. The Type-based version already knows the type to use, so no search is necessary. It could be in any namespace or assembly, but the implication of typeof is that you could also have used "new".
The Type approach makes more sense when you will have a Type supplied at runtime, but not usually that close to the object creation.
An obvious "problem" is that the former is stringly typed which is rarely a good thing, but it has the situational advantage of being runtime type checked so you have a level of dynamism. Personally, the refactor-factor outweighs dynamic design concerns mostly.
In the first instance you could use that methodology to create an instance dynamically without knowing the type at run time. Where as the second one you need to know the type when you're writing the code.
精彩评论