从Type类型中获取对应默认值的最优实现方式是什么?
C# 根据Type实例获取对应类型默认值的实现方案
核心实现代码
直接通过类型的值类型判断和可空类型判断就能覆盖所有场景,实现如下:
public static object GetDefaultValue(Type type) { // 引用类型直接返回null if (!type.IsValueType) return null; // 可空值类型(Nullable<T>)返回null if (Nullable.GetUnderlyingType(type) != null) return null; // 普通值类型返回对应默认实例 return Activator.CreateInstance(type); }
常见场景验证结果
- 传入
typeof(string)(引用类型):返回null - 传入
typeof(int?)(可空值类型):返回null - 传入
typeof(int):返回0 - 传入
typeof(DateTime):返回0001/1/1 0:00:00 - 传入
typeof(decimal):返回0.0M - 传入自定义结构体类型:返回所有字段为默认值的结构体实例
高性能优化方案
如果需要高频调用该方法,可以加缓存避免重复反射的开销:
using System.Collections.Concurrent; private static readonly ConcurrentDictionary<Type, object> _defaultValueCache = new ConcurrentDictionary<Type, object>(); public static object GetDefaultValueCached(Type type) { return _defaultValueCache.GetOrAdd(type, t => { if (!t.IsValueType || Nullable.GetUnderlyingType(t) != null) return null; return Activator.CreateInstance(t); }); }
内容的提问来源于stack exchange,提问作者Dilshod K
相关产品推荐
相关产品推荐

