-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>
public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{
var t = writer.WriteStartObjectAsync(cancellationToken);
Task t = writer.WriteStartObjectAsync(cancellationToken);
if (!t.IsCompletedSucessfully())
{
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
{
@@ -275,8 +275,7 @@ namespace Newtonsoft.Json.Serialization
// serialize all fields
foreach (MemberInfo member in allMembers)
{
FieldInfo field = member as FieldInfo;
if (field != null && !field.IsStatic)
if (member is FieldInfo field && !field.IsStatic)
{
serializableMembers.Add(member);
}
@@ -426,8 +425,7 @@ namespace Newtonsoft.Json.Serialization
Type t = ReflectionUtils.GetMemberUnderlyingType(m);
Type dictionaryType;
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType))
{
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
@@ -454,8 +452,7 @@ namespace Newtonsoft.Json.Serialization
Type t = ReflectionUtils.GetMemberUnderlyingType(member);
Type dictionaryType;
ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType);
ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType);
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
@@ -590,7 +587,7 @@ namespace Newtonsoft.Json.Serialization
{
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)
{
return null;
@@ -691,8 +688,7 @@ namespace Newtonsoft.Json.Serialization
property.PropertyType = parameterInfo.ParameterType;
property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo);
bool allowNonPublicAccess;
SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess);
SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _);
property.Readable = false;
property.Writable = true;
@@ -776,13 +772,13 @@ namespace Newtonsoft.Json.Serialization
private void ResolveCallbackMethods(JsonContract contract, Type t)
{
List<SerializationCallback> onSerializing;
List<SerializationCallback> onSerialized;
List<SerializationCallback> onDeserializing;
List<SerializationCallback> onDeserialized;
List<SerializationErrorCallback> onError;
GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError);
GetCallbackMethodsForType(
t,
out List<SerializationCallback> onSerializing,
out List<SerializationCallback> onSerialized,
out List<SerializationCallback> onDeserializing,
out List<SerializationCallback> onDeserialized,
out List<SerializationErrorCallback> onError);
if (onSerializing != null)
{
@@ -1222,8 +1218,7 @@ namespace Newtonsoft.Json.Serialization
internal static bool CanConvertToString(Type type)
{
#if HAVE_TYPE_DESCRIPTOR
TypeConverter converter;
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter))
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out _))
{
return true;
}
@@ -1379,8 +1374,7 @@ namespace Newtonsoft.Json.Serialization
property.ValueProvider = CreateMemberValueProvider(member);
property.AttributeProvider = new ReflectionAttributeProvider(member);
bool allowNonPublicAccess;
SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess);
SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess);
if (memberSerialization != MemberSerialization.Fields)
{
@@ -35,11 +35,9 @@ namespace Newtonsoft.Json.Serialization
private BidirectionalDictionary<string, object> GetMappings(object context)
{
JsonSerializerInternalBase internalSerializer = context as JsonSerializerInternalBase;
if (internalSerializer == null)
if (!(context is JsonSerializerInternalBase internalSerializer))
{
JsonSerializerProxy proxy = context as JsonSerializerProxy;
if (proxy != null)
if (context is JsonSerializerProxy proxy)
{
internalSerializer = proxy.GetInternalSerializer();
}
@@ -54,8 +52,7 @@ namespace Newtonsoft.Json.Serialization
public object ResolveReference(object context, string reference)
{
object value;
GetMappings(context).TryGetByFirst(reference, out value);
GetMappings(context).TryGetByFirst(reference, out object value);
return value;
}
@@ -63,8 +60,7 @@ namespace Newtonsoft.Json.Serialization
{
BidirectionalDictionary<string, object> mappings = GetMappings(context);
string reference;
if (!mappings.TryGetBySecond(value, out reference))
if (!mappings.TryGetBySecond(value, out string reference))
{
_referenceCount++;
reference = _referenceCount.ToString(CultureInfo.InvariantCulture);
@@ -81,8 +77,7 @@ namespace Newtonsoft.Json.Serialization
public bool IsReferenced(object context, object value)
{
string reference;
return GetMappings(context).TryGetBySecond(value, out reference);
return GetMappings(context).TryGetBySecond(value, out _);
}
}
}
@@ -251,9 +251,11 @@ namespace Newtonsoft.Json.Serialization
}
#endif
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(
underlyingType,
CollectionItemType,
out Type immutableCreatedType,
out ObjectConstructor<object> immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
@@ -180,20 +180,21 @@ namespace Newtonsoft.Json.Serialization
#if (NET20 || NET35)
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
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType))
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _))
{
ShouldCreateWrapper = true;
}
}
#endif
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator))
if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(
underlyingType,
DictionaryKeyType,
DictionaryValueType,
out Type immutableCreatedType,
out ObjectConstructor<object> immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
@@ -25,12 +25,9 @@
#if HAVE_DYNAMIC
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities;
using System.Collections;
namespace Newtonsoft.Json.Serialization
{
@@ -60,8 +60,7 @@ namespace Newtonsoft.Json.Serialization
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JToken token = value as JToken;
if (token == null)
if (!(value is JToken token))
{
throw new ArgumentException("Value is not a JToken.", nameof(value));
}
@@ -156,8 +156,7 @@ namespace Newtonsoft.Json.Serialization
// KeyedCollection has an ordinal comparer
if (comparisonType == StringComparison.Ordinal)
{
JsonProperty property;
if (TryGetValue(propertyName, out property))
if (TryGetValue(propertyName, out JsonProperty property))
{
return property;
}
@@ -380,8 +380,7 @@ namespace Newtonsoft.Json.Serialization
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if HAVE_TYPE_DESCRIPTOR
TypeConverter converter;
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter))
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter))
{
s = converter.ConvertToInvariantString(value);
return true;
@@ -411,8 +410,7 @@ namespace Newtonsoft.Json.Serialization
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
TryConvertToString(value, contract.UnderlyingType, out string s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
@@ -453,10 +451,7 @@ namespace Newtonsoft.Json.Serialization
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
{
continue;
}
@@ -585,8 +580,7 @@ namespace Newtonsoft.Json.Serialization
private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
if (objectContract == null)
if (!(contract is JsonObjectContract objectContract))
{
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)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
@@ -904,10 +897,7 @@ namespace Newtonsoft.Json.Serialization
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
{
continue;
}
@@ -931,8 +921,7 @@ namespace Newtonsoft.Json.Serialization
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
if (contract.TryGetMember(value, memberName, out object memberValue))
{
try
{
@@ -1036,8 +1025,7 @@ namespace Newtonsoft.Json.Serialization
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
@@ -1064,8 +1052,7 @@ namespace Newtonsoft.Json.Serialization
{
DictionaryEntry entry = e.Entry;
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
@@ -1120,8 +1107,6 @@ namespace Newtonsoft.Json.Serialization
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
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;
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>
/// 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
{
@@ -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.Globalization;
using System.IO;
@@ -122,16 +147,14 @@ namespace Newtonsoft.Json.Serialization
bool IJsonLineInfo.HasLineInfo()
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return lineInfo != null && lineInfo.HasLineInfo();
return _innerReader is IJsonLineInfo lineInfo && lineInfo.HasLineInfo();
}
int IJsonLineInfo.LineNumber
{
get
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LineNumber : 0;
return (_innerReader is IJsonLineInfo lineInfo) ? lineInfo.LineNumber : 0;
}
}
@@ -139,8 +162,7 @@ namespace Newtonsoft.Json.Serialization
{
get
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LinePosition : 0;
return (_innerReader is IJsonLineInfo lineInfo) ? 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.Collections.Generic;
using System.Globalization;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Text;
namespace Newtonsoft.Json.Serialization
{
@@ -61,10 +61,7 @@ namespace Newtonsoft.Json.Utilities
public void Set(TFirst first, TSecond second)
{
TFirst existingFirst;
TSecond existingSecond;
if (_firstToSecond.TryGetValue(first, out existingSecond))
if (_firstToSecond.TryGetValue(first, out TSecond existingSecond))
{
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))
{
@@ -289,8 +289,7 @@ namespace Newtonsoft.Json.Utilities
}
object v = currentArray[0];
IList list = v as IList;
if (list != null)
if (v is IList list)
{
currentArray = list;
}
@@ -52,8 +52,7 @@ namespace Newtonsoft.Json.Utilities
{
ValidationUtils.ArgumentNotNull(list, nameof(list));
ICollection<T> collection = list as ICollection<T>;
if (collection != null)
if (list is ICollection<T> collection)
{
_genericCollection = collection;
}
@@ -30,8 +30,10 @@ using System.ComponentModel;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
#if !HAVE_GUID_TRY_PARSE
using System.Text;
using System.Text.RegularExpressions;
#endif
using Newtonsoft.Json.Serialization;
using System.Reflection;
#if !HAVE_LINQ
@@ -381,7 +383,7 @@ namespace Newtonsoft.Json.Utilities
}
#endif
#region TryConvert
#region TryConvert
internal enum ConvertResult
{
Success = 0,
@@ -447,7 +449,7 @@ namespace Newtonsoft.Json.Utilities
}
// 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())
{
@@ -468,9 +470,9 @@ namespace Newtonsoft.Json.Utilities
}
#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;
}
#endif
@@ -582,9 +584,9 @@ namespace Newtonsoft.Json.Utilities
value = null;
return ConvertResult.NoValidConversion;
}
#endregion
#endregion
#region ConvertOrCast
#region ConvertOrCast
/// <summary>
/// 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.
@@ -615,7 +617,7 @@ namespace Newtonsoft.Json.Utilities
return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType);
}
#endregion
#endregion
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)
{
long ticks;
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
if (!TryParseMicrosoftDate(text, out long ticks, out _, out DateTimeKind kind))
{
dt = default(DateTime);
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)
{
DateTime temp;
if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp))
if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTime temp))
{
temp = EnsureDateTime(temp, dateTimeZoneHandling);
dt = temp;
@@ -567,11 +562,7 @@ namespace Newtonsoft.Json.Utilities
#if HAVE_DATE_TIME_OFFSET
private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt)
{
long ticks;
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
if (!TryParseMicrosoftDate(text, out long ticks, out TimeSpan offset, out _))
{
dt = default(DateTime);
return false;
@@ -585,8 +576,7 @@ namespace Newtonsoft.Json.Utilities
private static bool TryParseDateTimeOffsetExact(string text, string dateFormatString, CultureInfo culture, out DateTimeOffset dt)
{
DateTimeOffset temp;
if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp))
if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTimeOffset temp))
{
dt = temp;
return true;
@@ -601,8 +591,7 @@ namespace Newtonsoft.Json.Utilities
{
bool negative = (offsetText[startIndex] == '-');
int hours;
if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success)
if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out int hours) != ParseResult.Success)
{
offset = default(TimeSpan);
return false;
@@ -698,10 +687,7 @@ namespace Newtonsoft.Json.Utilities
{
int length = 19;
int year;
int month;
int day;
GetDateValues(dt, out year, out month, out day);
GetDateValues(dt, out int year, out int month, out int day);
CopyIntToCharArray(chars, start, year, 4);
chars[start + 4] = '-';
@@ -376,7 +376,7 @@ namespace Newtonsoft.Json.Utilities
{
object value = _dictionary[item.Key];
if (object.Equals(value, item.Value))
if (Equals(value, item.Value))
{
_dictionary.Remove(item.Key);
return true;
@@ -24,12 +24,8 @@
#endregion
#if HAVE_DYNAMIC
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Newtonsoft.Json.Utilities
{
@@ -184,7 +184,7 @@ namespace Newtonsoft.Json.Utilities
private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
{
var exp = value.Expression;
Expression exp = value.Expression;
return new[]
{
Expression.NewArrayInit(typeof(object), GetArgs(args)),
@@ -38,9 +38,7 @@ namespace Newtonsoft.Json.Utilities
{
internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly DynamicReflectionDelegateFactory _instance = new DynamicReflectionDelegateFactory();
internal static DynamicReflectionDelegateFactory Instance => _instance;
internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory();
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;
#endif
string s;
if (map.TryGetBySecond(n2, out s))
if (map.TryGetBySecond(n2, out _))
{
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;
BidirectionalDictionary<string, string> map = EnumMemberNamesPerType.Get(t);
string resolvedEnumName;
if (TryResolvedEnumName(map, enumText, out resolvedEnumName))
if (TryResolvedEnumName(map, enumText, out string resolvedEnumName))
{
finalEnumText = resolvedEnumName;
}
@@ -242,8 +240,7 @@ namespace Newtonsoft.Json.Utilities
{
string name = names[i].Trim();
string resolvedEnumName;
map.TryGetByFirst(name, out resolvedEnumName);
map.TryGetByFirst(name, out string resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? name;
if (camelCaseText)
+4 -8
View File
@@ -27,17 +27,13 @@ namespace Newtonsoft.Json.Utilities
{
internal class EnumValue<T> where T : struct
{
private readonly string _name;
private readonly T _value;
public string Name => _name;
public T Value => _value;
public string Name { get; }
public T Value { get; }
public EnumValue(string name, T value)
{
_name = name;
_value = value;
Name = name;
Value = value;
}
}
}
@@ -39,10 +39,7 @@ namespace Newtonsoft.Json.Utilities
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
internal static ReflectionDelegateFactory Instance => _instance;
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
@@ -23,9 +23,6 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Text;
namespace Newtonsoft.Json.Utilities
{
internal static class JsonTokenUtils
@@ -108,18 +108,14 @@ namespace Newtonsoft.Json.Utilities
public static string GetPrefix(string qualifiedName)
{
string prefix;
string localName;
GetQualifiedNameParts(qualifiedName, out prefix, out localName);
GetQualifiedNameParts(qualifiedName, out string prefix, out _);
return prefix;
}
public static string GetLocalName(string qualifiedName)
{
string prefix;
string localName;
GetQualifiedNameParts(qualifiedName, out prefix, out localName);
GetQualifiedNameParts(qualifiedName, out _, out string localName);
return localName;
}
@@ -38,14 +38,12 @@ namespace Newtonsoft.Json.Utilities
{
public Func<T, object> CreateGet<T>(MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
if (memberInfo is PropertyInfo propertyInfo)
{
return CreateGet<T>(propertyInfo);
}
FieldInfo fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
if (memberInfo is FieldInfo fieldInfo)
{
return CreateGet<T>(fieldInfo);
}
@@ -55,14 +53,12 @@ namespace Newtonsoft.Json.Utilities
public Action<T, object> CreateSet<T>(MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
if (memberInfo is PropertyInfo propertyInfo)
{
return CreateSet<T>(propertyInfo);
}
FieldInfo fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
if (memberInfo is FieldInfo fieldInfo)
{
return CreateSet<T>(fieldInfo);
}
@@ -26,7 +26,6 @@
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Globalization;
#if !HAVE_LINQ
@@ -31,8 +31,6 @@ using System.Numerics;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
@@ -164,9 +162,7 @@ namespace Newtonsoft.Json.Utilities
{
if (binder != null)
{
string assemblyName;
string typeName;
binder.BindToName(t, out assemblyName, out typeName);
binder.BindToName(t, out string assemblyName, out string typeName);
#if (NET20 || NET35)
// for older SerializationBinder implementations that didn't have BindToName
if (assemblyName == null & typeName == null)
@@ -292,8 +288,7 @@ namespace Newtonsoft.Json.Utilities
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _);
}
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)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
return InheritsGenericDefinition(type, genericClassDefinition, out _);
}
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)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type genericListType))
{
if (genericListType.IsGenericTypeDefinition())
{
@@ -414,8 +407,7 @@ namespace Newtonsoft.Json.Utilities
{
ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition())
{
@@ -473,9 +465,7 @@ namespace Newtonsoft.Json.Utilities
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
if (member is PropertyInfo propertyInfo)
{
return IsIndexedProperty(propertyInfo);
}
@@ -821,36 +811,31 @@ namespace Newtonsoft.Json.Utilities
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)
? t.GetTypeInfo().GetCustomAttributes(attributeType, 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();
}
if (provider is MemberInfo)
if (provider is MemberInfo memberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray();
return (attributeType != null) ? memberInfo.GetCustomAttributes(attributeType, inherit).ToArray() : memberInfo.GetCustomAttributes(inherit).ToArray();
}
if (provider is Module)
if (provider is Module module)
{
Module m = (Module)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray();
return (attributeType != null) ? module.GetCustomAttributes(attributeType).ToArray() : module.GetCustomAttributes().ToArray();
}
if (provider is ParameterInfo)
if (provider is ParameterInfo parameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray();
return (attributeType != null) ? parameterInfo.GetCustomAttributes(attributeType, inherit).ToArray() : parameterInfo.GetCustomAttributes(inherit).ToArray();
}
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
@@ -63,8 +63,7 @@ namespace Newtonsoft.Json.Utilities
#if HAVE_CONCURRENT_DICTIONARY
return _concurrentStore.GetOrAdd(key, _creator);
#else
TValue value;
if (!_store.TryGetValue(key, out value))
if (!_store.TryGetValue(key, out TValue value))
{
return AddValue(key);
}
@@ -88,8 +87,7 @@ namespace Newtonsoft.Json.Utilities
else
{
// double check locking
TValue checkValue;
if (_store.TryGetValue(key, out checkValue))
if (_store.TryGetValue(key, out TValue checkValue))
{
return checkValue;
}