开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜