Programmatic equivalent of default(Type)

前端 未结 14 1909
时光取名叫无心
时光取名叫无心 2020-11-22 05:28

I\'m using reflection to loop through a Type\'s properties and set certain types to their default. Now, I could do a switch on the type and set the defau

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 06:10

    This is optimized Flem's solution:

    using System.Collections.Concurrent;
    
    namespace System
    {
        public static class TypeExtension
        {
            //a thread-safe way to hold default instances created at run-time
            private static ConcurrentDictionary typeDefaults =
               new ConcurrentDictionary();
    
            public static object GetDefaultValue(this Type type)
            {
                return type.IsValueType
                   ? typeDefaults.GetOrAdd(type, Activator.CreateInstance)
                   : null;
            }
        }
    }
    

提交回复
热议问题