How do I create an instance and assign a default value based on a Type parameter?
I have a开发者_运维问答n array of Type
objects corresponding to int
, bool
, string
, float
, int?
...
How do I write a function that takes in the above array and returns strongly typed default values for each type in the array?
To get a default value from a Type
, simply invoke Activator.CreateInstance
object obj = Activator.CreateInstance(theType);
As for the bit about getting a strong type, the problem is that when you use reflection in this manner, it deals in objects. To get a strong type, you would need to know it at compile time, which kind of defeats your purpose. When you're doing these things at runtime, you're left with object
or dynamic
(which is just object
behind the scenes).
Beyond that, if you're talking about running the array through a method and returning default values for each type, you're going to be talking about returning an IEnumerable<object>
or object[]
array, as the type of each item would obviously differ.
精彩评论