-Refactor

This commit is contained in:
James Newton-King
2017-10-23 10:33:35 +13:00
parent 9932155295
commit 473a7721bd
32 changed files with 228 additions and 198 deletions
+1 -1
View File
@@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
var t = writer.WriteStartObjectAsync(cancellationToken); Task t = writer.WriteStartObjectAsync(cancellationToken);
if (!t.IsCompletedSucessfully()) if (!t.IsCompletedSucessfully())
{ {
return AwaitProperties(t, 0, writer, cancellationToken, converters); return AwaitProperties(t, 0, writer, cancellationToken, converters);
@@ -1,4 +1,29 @@
using Newtonsoft.Json.Utilities; #region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -275,8 +275,7 @@ namespace Newtonsoft.Json.Serialization
// serialize all fields // serialize all fields
foreach (MemberInfo member in allMembers) foreach (MemberInfo member in allMembers)
{ {
FieldInfo field = member as FieldInfo; if (member is FieldInfo field && !field.IsStatic)
if (field != null && !field.IsStatic)
{ {
serializableMembers.Add(member); serializableMembers.Add(member);
} }
@@ -426,8 +425,7 @@ namespace Newtonsoft.Json.Serialization
Type t = ReflectionUtils.GetMemberUnderlyingType(m); Type t = ReflectionUtils.GetMemberUnderlyingType(m);
Type dictionaryType; if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType))
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
{ {
Type keyType = dictionaryType.GetGenericArguments()[0]; Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1]; Type valueType = dictionaryType.GetGenericArguments()[1];
@@ -454,8 +452,7 @@ namespace Newtonsoft.Json.Serialization
Type t = ReflectionUtils.GetMemberUnderlyingType(member); Type t = ReflectionUtils.GetMemberUnderlyingType(member);
Type dictionaryType; ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType);
ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType);
Type keyType = dictionaryType.GetGenericArguments()[0]; Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1]; Type valueType = dictionaryType.GetGenericArguments()[1];
@@ -590,7 +587,7 @@ namespace Newtonsoft.Json.Serialization
{ {
foreach (ParameterInfo parameterInfo in parameters) foreach (ParameterInfo parameterInfo in parameters)
{ {
var memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); JsonProperty memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType);
if (memberProperty == null || memberProperty.Writable) if (memberProperty == null || memberProperty.Writable)
{ {
return null; return null;
@@ -691,8 +688,7 @@ namespace Newtonsoft.Json.Serialization
property.PropertyType = parameterInfo.ParameterType; property.PropertyType = parameterInfo.ParameterType;
property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo); property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo);
bool allowNonPublicAccess; SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _);
SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess);
property.Readable = false; property.Readable = false;
property.Writable = true; property.Writable = true;
@@ -776,13 +772,13 @@ namespace Newtonsoft.Json.Serialization
private void ResolveCallbackMethods(JsonContract contract, Type t) private void ResolveCallbackMethods(JsonContract contract, Type t)
{ {
List<SerializationCallback> onSerializing; GetCallbackMethodsForType(
List<SerializationCallback> onSerialized; t,
List<SerializationCallback> onDeserializing; out List<SerializationCallback> onSerializing,
List<SerializationCallback> onDeserialized; out List<SerializationCallback> onSerialized,
List<SerializationErrorCallback> onError; out List<SerializationCallback> onDeserializing,
out List<SerializationCallback> onDeserialized,
GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError); out List<SerializationErrorCallback> onError);
if (onSerializing != null) if (onSerializing != null)
{ {
@@ -1222,8 +1218,7 @@ namespace Newtonsoft.Json.Serialization
internal static bool CanConvertToString(Type type) internal static bool CanConvertToString(Type type)
{ {
#if HAVE_TYPE_DESCRIPTOR #if HAVE_TYPE_DESCRIPTOR
TypeConverter converter; if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out _))
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter))
{ {
return true; return true;
} }
@@ -1379,8 +1374,7 @@ namespace Newtonsoft.Json.Serialization
property.ValueProvider = CreateMemberValueProvider(member); property.ValueProvider = CreateMemberValueProvider(member);
property.AttributeProvider = new ReflectionAttributeProvider(member); property.AttributeProvider = new ReflectionAttributeProvider(member);
bool allowNonPublicAccess; SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess);
SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess);
if (memberSerialization != MemberSerialization.Fields) if (memberSerialization != MemberSerialization.Fields)
{ {
@@ -35,11 +35,9 @@ namespace Newtonsoft.Json.Serialization
private BidirectionalDictionary<string, object> GetMappings(object context) private BidirectionalDictionary<string, object> GetMappings(object context)
{ {
JsonSerializerInternalBase internalSerializer = context as JsonSerializerInternalBase; if (!(context is JsonSerializerInternalBase internalSerializer))
if (internalSerializer == null)
{ {
JsonSerializerProxy proxy = context as JsonSerializerProxy; if (context is JsonSerializerProxy proxy)
if (proxy != null)
{ {
internalSerializer = proxy.GetInternalSerializer(); internalSerializer = proxy.GetInternalSerializer();
} }
@@ -54,8 +52,7 @@ namespace Newtonsoft.Json.Serialization
public object ResolveReference(object context, string reference) public object ResolveReference(object context, string reference)
{ {
object value; GetMappings(context).TryGetByFirst(reference, out object value);
GetMappings(context).TryGetByFirst(reference, out value);
return value; return value;
} }
@@ -63,8 +60,7 @@ namespace Newtonsoft.Json.Serialization
{ {
BidirectionalDictionary<string, object> mappings = GetMappings(context); BidirectionalDictionary<string, object> mappings = GetMappings(context);
string reference; if (!mappings.TryGetBySecond(value, out string reference))
if (!mappings.TryGetBySecond(value, out reference))
{ {
_referenceCount++; _referenceCount++;
reference = _referenceCount.ToString(CultureInfo.InvariantCulture); reference = _referenceCount.ToString(CultureInfo.InvariantCulture);
@@ -81,8 +77,7 @@ namespace Newtonsoft.Json.Serialization
public bool IsReferenced(object context, object value) public bool IsReferenced(object context, object value)
{ {
string reference; return GetMappings(context).TryGetBySecond(value, out _);
return GetMappings(context).TryGetBySecond(value, out reference);
} }
} }
} }
@@ -251,9 +251,11 @@ namespace Newtonsoft.Json.Serialization
} }
#endif #endif
Type immutableCreatedType; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(
ObjectConstructor<object> immutableParameterizedCreator; underlyingType,
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) CollectionItemType,
out Type immutableCreatedType,
out ObjectConstructor<object> immutableParameterizedCreator))
{ {
CreatedType = immutableCreatedType; CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator; _parameterizedCreator = immutableParameterizedCreator;
@@ -180,20 +180,21 @@ namespace Newtonsoft.Json.Serialization
#if (NET20 || NET35) #if (NET20 || NET35)
if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType))
{ {
Type tempDictioanryType;
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead // wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _))
{ {
ShouldCreateWrapper = true; ShouldCreateWrapper = true;
} }
} }
#endif #endif
Type immutableCreatedType; if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(
ObjectConstructor<object> immutableParameterizedCreator; underlyingType,
if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) DictionaryKeyType,
DictionaryValueType,
out Type immutableCreatedType,
out ObjectConstructor<object> immutableParameterizedCreator))
{ {
CreatedType = immutableCreatedType; CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator; _parameterizedCreator = immutableParameterizedCreator;
@@ -25,12 +25,9 @@
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System; using System;
using System.Collections.Generic;
using System.Dynamic; using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Collections;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -60,8 +60,7 @@ namespace Newtonsoft.Json.Serialization
{ {
ValidationUtils.ArgumentNotNull(value, nameof(value)); ValidationUtils.ArgumentNotNull(value, nameof(value));
JToken token = value as JToken; if (!(value is JToken token))
if (token == null)
{ {
throw new ArgumentException("Value is not a JToken.", nameof(value)); throw new ArgumentException("Value is not a JToken.", nameof(value));
} }
@@ -156,8 +156,7 @@ namespace Newtonsoft.Json.Serialization
// KeyedCollection has an ordinal comparer // KeyedCollection has an ordinal comparer
if (comparisonType == StringComparison.Ordinal) if (comparisonType == StringComparison.Ordinal)
{ {
JsonProperty property; if (TryGetValue(propertyName, out JsonProperty property))
if (TryGetValue(propertyName, out property))
{ {
return property; return property;
} }
@@ -380,8 +380,7 @@ namespace Newtonsoft.Json.Serialization
internal static bool TryConvertToString(object value, Type type, out string s) internal static bool TryConvertToString(object value, Type type, out string s)
{ {
#if HAVE_TYPE_DESCRIPTOR #if HAVE_TYPE_DESCRIPTOR
TypeConverter converter; if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter))
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter))
{ {
s = converter.ConvertToInvariantString(value); s = converter.ConvertToInvariantString(value);
return true; return true;
@@ -411,8 +410,7 @@ namespace Newtonsoft.Json.Serialization
{ {
OnSerializing(writer, contract, value); OnSerializing(writer, contract, value);
string s; TryConvertToString(value, contract.UnderlyingType, out string s);
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s); writer.WriteValue(s);
OnSerialized(writer, contract, value); OnSerialized(writer, contract, value);
@@ -453,10 +451,7 @@ namespace Newtonsoft.Json.Serialization
JsonProperty property = contract.Properties[index]; JsonProperty property = contract.Properties[index];
try try
{ {
object memberValue; if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{ {
continue; continue;
} }
@@ -585,8 +580,7 @@ namespace Newtonsoft.Json.Serialization
private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property) private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property)
{ {
JsonObjectContract objectContract = contract as JsonObjectContract; if (!(contract is JsonObjectContract objectContract))
if (objectContract == null)
{ {
return false; return false;
} }
@@ -668,8 +662,7 @@ namespace Newtonsoft.Json.Serialization
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{ {
IWrappedCollection wrappedCollection = values as IWrappedCollection; object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList); OnSerializing(writer, contract, underlyingList);
@@ -904,10 +897,7 @@ namespace Newtonsoft.Json.Serialization
{ {
try try
{ {
object memberValue; if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{ {
continue; continue;
} }
@@ -931,8 +921,7 @@ namespace Newtonsoft.Json.Serialization
foreach (string memberName in value.GetDynamicMemberNames()) foreach (string memberName in value.GetDynamicMemberNames())
{ {
object memberValue; if (contract.TryGetMember(value, memberName, out object memberValue))
if (contract.TryGetMember(value, memberName, out memberValue))
{ {
try try
{ {
@@ -1036,8 +1025,7 @@ namespace Newtonsoft.Json.Serialization
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{ {
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary); OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary); _serializeStack.Add(underlyingDictionary);
@@ -1064,8 +1052,7 @@ namespace Newtonsoft.Json.Serialization
{ {
DictionaryEntry entry = e.Entry; DictionaryEntry entry = e.Entry;
bool escape; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.DictionaryKeyResolver != null) propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName) ? contract.DictionaryKeyResolver(propertyName)
@@ -1120,8 +1107,6 @@ namespace Newtonsoft.Json.Serialization
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{ {
string propertyName;
if (contract.ContractType == JsonContractType.Primitive) if (contract.ContractType == JsonContractType.Primitive)
{ {
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
@@ -1170,7 +1155,7 @@ namespace Newtonsoft.Json.Serialization
} }
} }
} }
else if (TryConvertToString(name, name.GetType(), out propertyName)) else if (TryConvertToString(name, name.GetType(), out string propertyName))
{ {
escape = true; escape = true;
return propertyName; return propertyName;
@@ -1,4 +1,29 @@
namespace Newtonsoft.Json.Serialization #region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Serialization
{ {
/// <summary> /// <summary>
/// A base class for resolving how property names and dictionary keys are serialized. /// A base class for resolving how property names and dictionary keys are serialized.
@@ -1,4 +1,29 @@
using Newtonsoft.Json.Utilities; #region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -1,4 +1,29 @@
using System; #region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
@@ -122,16 +147,14 @@ namespace Newtonsoft.Json.Serialization
bool IJsonLineInfo.HasLineInfo() bool IJsonLineInfo.HasLineInfo()
{ {
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; return _innerReader is IJsonLineInfo lineInfo && lineInfo.HasLineInfo();
return lineInfo != null && lineInfo.HasLineInfo();
} }
int IJsonLineInfo.LineNumber int IJsonLineInfo.LineNumber
{ {
get get
{ {
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; return (_innerReader is IJsonLineInfo lineInfo) ? lineInfo.LineNumber : 0;
return (lineInfo != null) ? lineInfo.LineNumber : 0;
} }
} }
@@ -139,8 +162,7 @@ namespace Newtonsoft.Json.Serialization
{ {
get get
{ {
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; return (_innerReader is IJsonLineInfo lineInfo) ? lineInfo.LinePosition : 0;
return (lineInfo != null) ? lineInfo.LinePosition : 0;
} }
} }
} }
@@ -1,11 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System; using System;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
#if HAVE_BIG_INTEGER #if HAVE_BIG_INTEGER
using System.Numerics; using System.Numerics;
#endif #endif
using System.Text;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -61,10 +61,7 @@ namespace Newtonsoft.Json.Utilities
public void Set(TFirst first, TSecond second) public void Set(TFirst first, TSecond second)
{ {
TFirst existingFirst; if (_firstToSecond.TryGetValue(first, out TSecond existingSecond))
TSecond existingSecond;
if (_firstToSecond.TryGetValue(first, out existingSecond))
{ {
if (!existingSecond.Equals(second)) if (!existingSecond.Equals(second))
{ {
@@ -72,7 +69,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
if (_secondToFirst.TryGetValue(second, out existingFirst)) if (_secondToFirst.TryGetValue(second, out TFirst existingFirst))
{ {
if (!existingFirst.Equals(first)) if (!existingFirst.Equals(first))
{ {
@@ -289,8 +289,7 @@ namespace Newtonsoft.Json.Utilities
} }
object v = currentArray[0]; object v = currentArray[0];
IList list = v as IList; if (v is IList list)
if (list != null)
{ {
currentArray = list; currentArray = list;
} }
@@ -52,8 +52,7 @@ namespace Newtonsoft.Json.Utilities
{ {
ValidationUtils.ArgumentNotNull(list, nameof(list)); ValidationUtils.ArgumentNotNull(list, nameof(list));
ICollection<T> collection = list as ICollection<T>; if (list is ICollection<T> collection)
if (collection != null)
{ {
_genericCollection = collection; _genericCollection = collection;
} }
@@ -30,8 +30,10 @@ using System.ComponentModel;
#if HAVE_BIG_INTEGER #if HAVE_BIG_INTEGER
using System.Numerics; using System.Numerics;
#endif #endif
#if !HAVE_GUID_TRY_PARSE
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
#endif
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Reflection; using System.Reflection;
#if !HAVE_LINQ #if !HAVE_LINQ
@@ -381,7 +383,7 @@ namespace Newtonsoft.Json.Utilities
} }
#endif #endif
#region TryConvert #region TryConvert
internal enum ConvertResult internal enum ConvertResult
{ {
Success = 0, Success = 0,
@@ -447,7 +449,7 @@ namespace Newtonsoft.Json.Utilities
} }
// use Convert.ChangeType if both types are IConvertible // use Convert.ChangeType if both types are IConvertible
if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType)) if (IsConvertible(initialValue.GetType()) && IsConvertible(targetType))
{ {
if (targetType.IsEnum()) if (targetType.IsEnum())
{ {
@@ -468,9 +470,9 @@ namespace Newtonsoft.Json.Utilities
} }
#if HAVE_DATE_TIME_OFFSET #if HAVE_DATE_TIME_OFFSET
if (initialValue is DateTime && targetType == typeof(DateTimeOffset)) if (initialValue is DateTime dt && targetType == typeof(DateTimeOffset))
{ {
value = new DateTimeOffset((DateTime)initialValue); value = new DateTimeOffset(dt);
return ConvertResult.Success; return ConvertResult.Success;
} }
#endif #endif
@@ -582,9 +584,9 @@ namespace Newtonsoft.Json.Utilities
value = null; value = null;
return ConvertResult.NoValidConversion; return ConvertResult.NoValidConversion;
} }
#endregion #endregion
#region ConvertOrCast #region ConvertOrCast
/// <summary> /// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the /// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type. /// value is checked whether it assignable to the specified type.
@@ -615,7 +617,7 @@ namespace Newtonsoft.Json.Utilities
return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType);
} }
#endregion #endregion
private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) private static object EnsureTypeAssignable(object value, Type initialType, Type targetType)
{ {
+6 -20
View File
@@ -521,11 +521,7 @@ namespace Newtonsoft.Json.Utilities
private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt) private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt)
{ {
long ticks; if (!TryParseMicrosoftDate(text, out long ticks, out _, out DateTimeKind kind))
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
{ {
dt = default(DateTime); dt = default(DateTime);
return false; return false;
@@ -552,8 +548,7 @@ namespace Newtonsoft.Json.Utilities
private static bool TryParseDateTimeExact(string text, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) private static bool TryParseDateTimeExact(string text, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt)
{ {
DateTime temp; if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTime temp))
if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp))
{ {
temp = EnsureDateTime(temp, dateTimeZoneHandling); temp = EnsureDateTime(temp, dateTimeZoneHandling);
dt = temp; dt = temp;
@@ -567,11 +562,7 @@ namespace Newtonsoft.Json.Utilities
#if HAVE_DATE_TIME_OFFSET #if HAVE_DATE_TIME_OFFSET
private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt) private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt)
{ {
long ticks; if (!TryParseMicrosoftDate(text, out long ticks, out TimeSpan offset, out _))
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
{ {
dt = default(DateTime); dt = default(DateTime);
return false; return false;
@@ -585,8 +576,7 @@ namespace Newtonsoft.Json.Utilities
private static bool TryParseDateTimeOffsetExact(string text, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) private static bool TryParseDateTimeOffsetExact(string text, string dateFormatString, CultureInfo culture, out DateTimeOffset dt)
{ {
DateTimeOffset temp; if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTimeOffset temp))
if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp))
{ {
dt = temp; dt = temp;
return true; return true;
@@ -601,8 +591,7 @@ namespace Newtonsoft.Json.Utilities
{ {
bool negative = (offsetText[startIndex] == '-'); bool negative = (offsetText[startIndex] == '-');
int hours; if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out int hours) != ParseResult.Success)
if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success)
{ {
offset = default(TimeSpan); offset = default(TimeSpan);
return false; return false;
@@ -698,10 +687,7 @@ namespace Newtonsoft.Json.Utilities
{ {
int length = 19; int length = 19;
int year; GetDateValues(dt, out int year, out int month, out int day);
int month;
int day;
GetDateValues(dt, out year, out month, out day);
CopyIntToCharArray(chars, start, year, 4); CopyIntToCharArray(chars, start, year, 4);
chars[start + 4] = '-'; chars[start + 4] = '-';
@@ -376,7 +376,7 @@ namespace Newtonsoft.Json.Utilities
{ {
object value = _dictionary[item.Key]; object value = _dictionary[item.Key];
if (object.Equals(value, item.Value)) if (Equals(value, item.Value))
{ {
_dictionary.Remove(item.Key); _dictionary.Remove(item.Key);
return true; return true;
@@ -24,12 +24,8 @@
#endregion #endregion
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Dynamic; using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
{ {
@@ -184,7 +184,7 @@ namespace Newtonsoft.Json.Utilities
private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
{ {
var exp = value.Expression; Expression exp = value.Expression;
return new[] return new[]
{ {
Expression.NewArrayInit(typeof(object), GetArgs(args)), Expression.NewArrayInit(typeof(object), GetArgs(args)),
@@ -38,9 +38,7 @@ namespace Newtonsoft.Json.Utilities
{ {
internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory
{ {
private static readonly DynamicReflectionDelegateFactory _instance = new DynamicReflectionDelegateFactory(); internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory();
internal static DynamicReflectionDelegateFactory Instance => _instance;
private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner)
{ {
+3 -6
View File
@@ -60,8 +60,7 @@ namespace Newtonsoft.Json.Utilities
n2 = f.Name; n2 = f.Name;
#endif #endif
string s; if (map.TryGetBySecond(n2, out _))
if (map.TryGetBySecond(n2, out s))
{ {
throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name)); throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name));
} }
@@ -196,8 +195,7 @@ namespace Newtonsoft.Json.Utilities
string finalEnumText; string finalEnumText;
BidirectionalDictionary<string, string> map = EnumMemberNamesPerType.Get(t); BidirectionalDictionary<string, string> map = EnumMemberNamesPerType.Get(t);
string resolvedEnumName; if (TryResolvedEnumName(map, enumText, out string resolvedEnumName))
if (TryResolvedEnumName(map, enumText, out resolvedEnumName))
{ {
finalEnumText = resolvedEnumName; finalEnumText = resolvedEnumName;
} }
@@ -242,8 +240,7 @@ namespace Newtonsoft.Json.Utilities
{ {
string name = names[i].Trim(); string name = names[i].Trim();
string resolvedEnumName; map.TryGetByFirst(name, out string resolvedEnumName);
map.TryGetByFirst(name, out resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? name; resolvedEnumName = resolvedEnumName ?? name;
if (camelCaseText) if (camelCaseText)
+4 -8
View File
@@ -27,17 +27,13 @@ namespace Newtonsoft.Json.Utilities
{ {
internal class EnumValue<T> where T : struct internal class EnumValue<T> where T : struct
{ {
private readonly string _name; public string Name { get; }
private readonly T _value; public T Value { get; }
public string Name => _name;
public T Value => _value;
public EnumValue(string name, T value) public EnumValue(string name, T value)
{ {
_name = name; Name = name;
_value = value; Value = value;
} }
} }
} }
@@ -39,10 +39,7 @@ namespace Newtonsoft.Json.Utilities
{ {
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory(); private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance internal static ReflectionDelegateFactory Instance => _instance;
{
get { return _instance; }
}
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{ {
@@ -23,9 +23,6 @@
// OTHER DEALINGS IN THE SOFTWARE. // OTHER DEALINGS IN THE SOFTWARE.
#endregion #endregion
using System;
using System.Text;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
{ {
internal static class JsonTokenUtils internal static class JsonTokenUtils
@@ -108,18 +108,14 @@ namespace Newtonsoft.Json.Utilities
public static string GetPrefix(string qualifiedName) public static string GetPrefix(string qualifiedName)
{ {
string prefix; GetQualifiedNameParts(qualifiedName, out string prefix, out _);
string localName;
GetQualifiedNameParts(qualifiedName, out prefix, out localName);
return prefix; return prefix;
} }
public static string GetLocalName(string qualifiedName) public static string GetLocalName(string qualifiedName)
{ {
string prefix; GetQualifiedNameParts(qualifiedName, out _, out string localName);
string localName;
GetQualifiedNameParts(qualifiedName, out prefix, out localName);
return localName; return localName;
} }
@@ -38,14 +38,12 @@ namespace Newtonsoft.Json.Utilities
{ {
public Func<T, object> CreateGet<T>(MemberInfo memberInfo) public Func<T, object> CreateGet<T>(MemberInfo memberInfo)
{ {
PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (memberInfo is PropertyInfo propertyInfo)
if (propertyInfo != null)
{ {
return CreateGet<T>(propertyInfo); return CreateGet<T>(propertyInfo);
} }
FieldInfo fieldInfo = memberInfo as FieldInfo; if (memberInfo is FieldInfo fieldInfo)
if (fieldInfo != null)
{ {
return CreateGet<T>(fieldInfo); return CreateGet<T>(fieldInfo);
} }
@@ -55,14 +53,12 @@ namespace Newtonsoft.Json.Utilities
public Action<T, object> CreateSet<T>(MemberInfo memberInfo) public Action<T, object> CreateSet<T>(MemberInfo memberInfo)
{ {
PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (memberInfo is PropertyInfo propertyInfo)
if (propertyInfo != null)
{ {
return CreateSet<T>(propertyInfo); return CreateSet<T>(propertyInfo);
} }
FieldInfo fieldInfo = memberInfo as FieldInfo; if (memberInfo is FieldInfo fieldInfo)
if (fieldInfo != null)
{ {
return CreateSet<T>(fieldInfo); return CreateSet<T>(fieldInfo);
} }
@@ -26,7 +26,6 @@
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection; using System.Reflection;
using System.Globalization; using System.Globalization;
#if !HAVE_LINQ #if !HAVE_LINQ
@@ -31,8 +31,6 @@ using System.Numerics;
using System.Reflection; using System.Reflection;
using System.Collections; using System.Collections;
using System.Globalization; using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text; using System.Text;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
@@ -164,9 +162,7 @@ namespace Newtonsoft.Json.Utilities
{ {
if (binder != null) if (binder != null)
{ {
string assemblyName; binder.BindToName(t, out string assemblyName, out string typeName);
string typeName;
binder.BindToName(t, out assemblyName, out typeName);
#if (NET20 || NET35) #if (NET20 || NET35)
// for older SerializationBinder implementations that didn't have BindToName // for older SerializationBinder implementations that didn't have BindToName
if (assemblyName == null & typeName == null) if (assemblyName == null & typeName == null)
@@ -292,8 +288,7 @@ namespace Newtonsoft.Json.Utilities
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{ {
Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _);
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
} }
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
@@ -340,8 +335,7 @@ namespace Newtonsoft.Json.Utilities
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{ {
Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out _);
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
} }
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
@@ -387,13 +381,12 @@ namespace Newtonsoft.Json.Utilities
public static Type GetCollectionItemType(Type type) public static Type GetCollectionItemType(Type type)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
Type genericListType;
if (type.IsArray) if (type.IsArray)
{ {
return type.GetElementType(); return type.GetElementType();
} }
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type genericListType))
{ {
if (genericListType.IsGenericTypeDefinition()) if (genericListType.IsGenericTypeDefinition())
{ {
@@ -414,8 +407,7 @@ namespace Newtonsoft.Json.Utilities
{ {
ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));
Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type genericDictionaryType))
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{ {
if (genericDictionaryType.IsGenericTypeDefinition()) if (genericDictionaryType.IsGenericTypeDefinition())
{ {
@@ -473,9 +465,7 @@ namespace Newtonsoft.Json.Utilities
{ {
ValidationUtils.ArgumentNotNull(member, nameof(member)); ValidationUtils.ArgumentNotNull(member, nameof(member));
PropertyInfo propertyInfo = member as PropertyInfo; if (member is PropertyInfo propertyInfo)
if (propertyInfo != null)
{ {
return IsIndexedProperty(propertyInfo); return IsIndexedProperty(propertyInfo);
} }
@@ -821,36 +811,31 @@ namespace Newtonsoft.Json.Utilities
public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit)
{ {
if (provider is Type) if (provider is Type t)
{ {
Type t = (Type)provider;
return (attributeType != null) return (attributeType != null)
? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray() ? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray()
: t.GetTypeInfo().GetCustomAttributes(inherit).ToArray(); : t.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
} }
if (provider is Assembly) if (provider is Assembly a)
{ {
Assembly a = (Assembly)provider;
return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray(); return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray();
} }
if (provider is MemberInfo) if (provider is MemberInfo memberInfo)
{ {
MemberInfo m = (MemberInfo)provider; return (attributeType != null) ? memberInfo.GetCustomAttributes(attributeType, inherit).ToArray() : memberInfo.GetCustomAttributes(inherit).ToArray();
return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray();
} }
if (provider is Module) if (provider is Module module)
{ {
Module m = (Module)provider; return (attributeType != null) ? module.GetCustomAttributes(attributeType).ToArray() : module.GetCustomAttributes().ToArray();
return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray();
} }
if (provider is ParameterInfo) if (provider is ParameterInfo parameterInfo)
{ {
ParameterInfo p = (ParameterInfo)provider; return (attributeType != null) ? parameterInfo.GetCustomAttributes(attributeType, inherit).ToArray() : parameterInfo.GetCustomAttributes(inherit).ToArray();
return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray();
} }
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
@@ -63,8 +63,7 @@ namespace Newtonsoft.Json.Utilities
#if HAVE_CONCURRENT_DICTIONARY #if HAVE_CONCURRENT_DICTIONARY
return _concurrentStore.GetOrAdd(key, _creator); return _concurrentStore.GetOrAdd(key, _creator);
#else #else
TValue value; if (!_store.TryGetValue(key, out TValue value))
if (!_store.TryGetValue(key, out value))
{ {
return AddValue(key); return AddValue(key);
} }
@@ -88,8 +87,7 @@ namespace Newtonsoft.Json.Utilities
else else
{ {
// double check locking // double check locking
TValue checkValue; if (_store.TryGetValue(key, out TValue checkValue))
if (_store.TryGetValue(key, out checkValue))
{ {
return checkValue; return checkValue;
} }