6767using System . Runtime . Serialization ;
6868using System . Text ;
6969using GitHub . Reflection ;
70+ using System . Diagnostics ;
7071
7172// ReSharper disable LoopCanBeConvertedToQuery
7273// ReSharper disable RedundantExplicitArrayCreation
@@ -1838,7 +1839,13 @@ public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo con
18381839 public static ConstructorDelegate GetConstructorByReflection ( Type type , params Type [ ] argsType )
18391840 {
18401841 ConstructorInfo constructorInfo = GetConstructorInfo ( type , argsType ) ;
1841- return constructorInfo == null ? null : GetConstructorByReflection ( constructorInfo ) ;
1842+ // if it's a value type (i.e., struct), it won't have a default constructor, so use Activator instead
1843+ return constructorInfo == null ? ( type . IsValueType ? GetConstructorForValueType ( type ) : null ) : GetConstructorByReflection ( constructorInfo ) ;
1844+ }
1845+
1846+ static ConstructorDelegate GetConstructorForValueType ( Type type )
1847+ {
1848+ return delegate ( object [ ] args ) { return Activator . CreateInstance ( type ) ; } ;
18421849 }
18431850
18441851#if ! SIMPLE_JSON_NO_LINQ_EXPRESSION
@@ -1865,7 +1872,8 @@ public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo con
18651872 public static ConstructorDelegate GetConstructorByExpression ( Type type , params Type [ ] argsType )
18661873 {
18671874 ConstructorInfo constructorInfo = GetConstructorInfo ( type , argsType ) ;
1868- return constructorInfo == null ? null : GetConstructorByExpression ( constructorInfo ) ;
1875+ // if it's a value type (i.e., struct), it won't have a default constructor, so use Activator instead
1876+ return constructorInfo == null ? ( type . IsValueType ? GetConstructorForValueType ( type ) : null ) : GetConstructorByExpression ( constructorInfo ) ;
18691877 }
18701878
18711879#endif
@@ -1925,6 +1933,9 @@ public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
19251933#if SIMPLE_JSON_NO_LINQ_EXPRESSION
19261934 return GetSetMethodByReflection ( propertyInfo ) ;
19271935#else
1936+ // if it's a struct, we want to use reflection, as linq expressions modify copies of the object and not the real thing
1937+ if ( propertyInfo . DeclaringType . IsValueType )
1938+ return GetSetMethodByReflection ( propertyInfo ) ;
19281939 return GetSetMethodByExpression ( propertyInfo ) ;
19291940#endif
19301941 }
@@ -1934,6 +1945,9 @@ public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
19341945#if SIMPLE_JSON_NO_LINQ_EXPRESSION
19351946 return GetSetMethodByReflection ( fieldInfo ) ;
19361947#else
1948+ // if it's a struct, we want to use reflection, as linq expressions modify copies of the object and not the real thing
1949+ if ( fieldInfo . DeclaringType . IsValueType )
1950+ return GetSetMethodByReflection ( fieldInfo ) ;
19371951 return GetSetMethodByExpression ( fieldInfo ) ;
19381952#endif
19391953 }
0 commit comments