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 资料的方法
Compiled expression is best way! (for performance to repeatedly create instance in runtime).
Statistics (2012):
Statistics (2015, .net 4.5, x64):
Statistics (2015, .net 4.5, x86):
Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):
Full code:
I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)
With generic method you can require that the type implements New().
With non-generic assume the type has a default constructor and catch an exception if it doesn't.
If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or
ConstructorInfo.Invoke()
. Two easy options for dynamic compilation are compiled Linq Expressions or some simpleIL
opcodes andDynamicMethod
. Either way, the difference is huge when you start getting into tight loops or multiple calls.Its pretty simple. Assume that your classname is
Car
and the namespace isVehicles
, then pass the parameter asVehicles.Car
which returns object of typeCar
. Like this you can create any instance of any class dynamically.If your Fully Qualified Name(ie,
Vehicles.Car
in this case) is in another assembly, theType.GetType
will be null. In such cases, you have loop through all assemblies and find theType
. For that you can use the below codeAnd you can get the instance by calling the above method.
Wouldn't the generic
T t = new T();
work?