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 object instance from a Type
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
If you want to use the default constructor then the solution using
System.Activator
presented earlier is probably the most convenient. However, if the type lacks a default constructor or you have to use a non-default one, then an option is to use reflection orSystem.ComponentModel.TypeDescriptor
. In case of reflection, it is enough to know just the type name (with its namespace).Example using reflection:
Example using
TypeDescriptor
:The
Activator
class within the rootSystem
namespace is pretty powerful.There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:
or (new path)
Here are some simple examples:
Without use of Reflection:
Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using
The
Activator
class has a generic variant that makes this a bit easier:One implementation of this problem is to attempt to call the parameter-less constructor of the Type:
Here is the same approach, contained in a generic method: