You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:36:03