开发者

Equivalent of default(T) using reflection [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C# - Programmatic equivalent of default(Type)

Is there a method or property in the Typ开发者_如何学Goe class (or elsewhere) that I can use to find the value of default(T)?


Just check type.IsValueType; if that is true use Activator.CreateInstance(type) - otherwise it is null.

It also helps that you can pass null to SetValue on a PropertyInfo or FieldInfo and it will work for value-types with even for int, float etc.


object obj = type.IsValueType ? Activator.CreateInstance(type) : null;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜