Programmatic equivalent of default(Type)

前端 未结 14 1808
时光取名叫无心
时光取名叫无心 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:26

    The Expressions can help here:

        private static Dictionary lambdasMap = new Dictionary();
    
        private object GetTypedNull(Type type)
        {
            Delegate func;
            if (!lambdasMap.TryGetValue(type, out func))
            {
                var body = Expression.Default(type);
                var lambda = Expression.Lambda(body);
                func = lambda.Compile();
                lambdasMap[type] = func;
            }
            return func.DynamicInvoke();
        }
    

    I did not test this snippet, but i think it should produce "typed" nulls for reference types..

提交回复
热议问题