From b62b5661e5aa3121a40c6b2ee7fa2dc3ddad4128 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Fri, 16 Feb 2018 14:39:43 -0500 Subject: [PATCH] Util method to cache a Type for JSON serialization --- ICD.Common.Utils/Json/JsonUtils.cs | 12 ++++++++++-- ICD.Common.Utils/ReflectionUtils.cs | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/ICD.Common.Utils/Json/JsonUtils.cs b/ICD.Common.Utils/Json/JsonUtils.cs index 2e0a46b..4b49dfe 100644 --- a/ICD.Common.Utils/Json/JsonUtils.cs +++ b/ICD.Common.Utils/Json/JsonUtils.cs @@ -29,8 +29,16 @@ namespace ICD.Common.Utils.Json public static void CacheType() where T : new() { - string serialized = JsonConvert.SerializeObject(ReflectionUtils.CreateInstance()); - JsonConvert.DeserializeObject(serialized); + CacheType(typeof(T)); + } + + /// + /// Forces Newtonsoft to cache the given type for faster subsequent usage. + /// + public static void CacheType(Type type) + { + string serialized = JsonConvert.SerializeObject(ReflectionUtils.CreateInstance(type)); + JsonConvert.DeserializeObject(serialized, type); } /// diff --git a/ICD.Common.Utils/ReflectionUtils.cs b/ICD.Common.Utils/ReflectionUtils.cs index 0aaeab0..2cd7c36 100644 --- a/ICD.Common.Utils/ReflectionUtils.cs +++ b/ICD.Common.Utils/ReflectionUtils.cs @@ -210,6 +210,26 @@ namespace ICD.Common.Utils : null; } + /// + /// Returns true if the given type has a public parameterless constructor. + /// + /// + /// + public static bool HasPublicParameterlessConstructor(Type type) + { + if (type == null) + throw new ArgumentNullException("type"); + + const BindingFlags binding = BindingFlags.Instance | BindingFlags.Public; + +#if SIMPLSHARP + return ((CType)type).GetConstructor(binding, null, new CType[0], null) +#else + return type.GetConstructor(binding, null, new Type[0], null) +#endif + != null; + } + /// /// Creates an instance of the given type, calling the default constructor. ///