private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { Type valueType = (value != null) ? value.GetType() : null; if (value != null) { if (targetType.IsAssignableFrom(valueType)) { return(value); } FuncNewton <object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType)); if (castConverter != null) { return(castConverter(value)); } } else { if (ReflectionUtils.IsNullable(targetType)) { return(null); } } throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); }
/// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues FuncNewton <JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return(Create(defaultSettings)); }
public ThreadSafeStore(FuncNewton <TKey, TValue> creator) { if (creator == null) { throw new ArgumentNullException(nameof(creator)); } _creator = creator; _store = new Dictionary <TKey, TValue>(); }
internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) { Type temporaryDictionaryType = typeof(Dictionary <,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object)); _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor <object>(temporaryDictionaryType); } return((IDictionary)_genericTemporaryDictionaryCreator()); }
public void ConstructorStruct() { FuncNewton <object> creator1 = DynamicReflectionDelegateFactory.Instance.CreateDefaultConstructor <object>(typeof(MyStruct)); MyStruct myStruct1 = (MyStruct)creator1.Invoke(); Assert.AreEqual(0, myStruct1.IntProperty); FuncNewton <MyStruct> creator2 = DynamicReflectionDelegateFactory.Instance.CreateDefaultConstructor <MyStruct>(typeof(MyStruct)); MyStruct myStruct2 = creator2.Invoke(); Assert.AreEqual(0, myStruct2.IntProperty); }
public void CreateGetWithBadObjectTarget() { ExceptionAssert.Throws <InvalidCastException>(() => { Person p = new Person(); p.Name = "Hi"; FuncNewton <object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateGet <object>(typeof(Movie).GetProperty("Name")); setter(p); }, "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'."); }
public static JsonConverter GetJsonConverter(object attributeProvider) { JsonConverterAttribute converterAttribute = GetCachedAttribute <JsonConverterAttribute>(attributeProvider); if (converterAttribute != null) { FuncNewton <object[], object> creator = CreatorCache.Get(converterAttribute.ConverterType); if (creator != null) { return((JsonConverter)creator(converterAttribute.ConverterParameters)); } } return(null); }
internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List <>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor <object>(temporaryListType); } return((IList)_genericTemporaryCollectionCreator()); }
/// <summary> /// Gets the value. /// </summary> /// <param name="target">The target to get the value from.</param> /// <returns>The value.</returns> public object GetValue(object target) { try { if (_getter == null) { _getter = DynamicReflectionDelegateFactory.Instance.CreateGet <object>(_memberInfo); } return(_getter(target)); } catch (Exception ex) { throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); } }
public override FuncNewton <T, object> CreateGet <T>(FieldInfo fieldInfo) { if (fieldInfo.IsLiteral) { object constantValue = fieldInfo.GetValue(null); FuncNewton <T, object> getter = o => constantValue; return(getter); } DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetFieldIL(fieldInfo, generator); return((FuncNewton <T, object>)dynamicMethod.CreateDelegate(typeof(FuncNewton <T, object>))); }
public static int IndexOf <T>(this IEnumerable <T> collection, FuncNewton <T, bool> predicate) { int index = 0; foreach (T value in collection) { if (predicate(value)) { return(index); } index++; } return(-1); }
private static FuncNewton <object[], object> GetCreator(Type type) { FuncNewton <object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor <object>(type) : null; return((parameters) => { try { if (parameters != null) { Type[] paramTypes = parameters.Select(param => param.GetType()).ToArray(); ConstructorInfo parameterizedConstructorInfo = type.GetConstructor(paramTypes); if (null != parameterizedConstructorInfo) { ObjectConstructor <object> parameterizedConstructor = ReflectionDelegateFactory.CreateParameterizedConstructor(parameterizedConstructorInfo); return parameterizedConstructor(parameters); } else { throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type)); } } if (defaultConstructor == null) { throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type)); } return defaultConstructor(); } catch (Exception ex) { throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, type), ex); } }); }
public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] converterArgs) { FuncNewton <object[], object> converterCreator = CreatorCache.Get(namingStrategyType); return((NamingStrategy)converterCreator(converterArgs)); }
/// <summary> /// Lookup and create an instance of the JsonConverter type described by the argument. /// </summary> /// <param name="converterType">The JsonConverter type to create.</param> /// <param name="converterArgs">Optional arguments to pass to an initializing constructor of the JsonConverter. /// If null, the default constructor is used.</param> public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] converterArgs) { FuncNewton <object[], object> converterCreator = CreatorCache.Get(converterType); return((JsonConverter)converterCreator(converterArgs)); }
public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames) { ReflectionObject d = new ReflectionObject(); ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; if (creator != null) { d.Creator = delegateFactory.CreateParameterizedConstructor(creator); } else { if (ReflectionUtils.HasDefaultConstructor(t, false)) { FuncNewton <object> ctor = delegateFactory.CreateDefaultConstructor <object>(t); d.Creator = args => ctor(); } } foreach (string memberName in memberNames) { MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public); if (members.Length != 1) { throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName)); } MemberInfo member = members.Single(); ReflectionMember reflectionMember = new ReflectionMember(); switch (member.MemberType()) { case MemberTypes.Field: case MemberTypes.Property: if (ReflectionUtils.CanReadMemberValue(member, false)) { reflectionMember.Getter = delegateFactory.CreateGet <object>(member); } if (ReflectionUtils.CanSetMemberValue(member, false, false)) { reflectionMember.Setter = delegateFactory.CreateSet <object>(member); } break; case MemberTypes.Method: MethodInfo method = (MethodInfo)member; if (method.IsPublic) { ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 0 && method.ReturnType != typeof(void)) { MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method); reflectionMember.Getter = target => call(target); } else if (parameters.Length == 1 && method.ReturnType == typeof(void)) { MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method); reflectionMember.Setter = (target, arg) => call(target, arg); } } break; default: throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name)); } if (ReflectionUtils.CanReadMemberValue(member, false)) { reflectionMember.Getter = delegateFactory.CreateGet <object>(member); } if (ReflectionUtils.CanSetMemberValue(member, false, false)) { reflectionMember.Setter = delegateFactory.CreateSet <object>(member); } reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member); d.Members[memberName] = reflectionMember; } return(d); }
public object GetValue(object target, string member) { FuncNewton <object, object> getter = Members[member].Getter; return(getter(target)); }
public static TSource ForgivingCaseSensitiveFind <TSource>(this IEnumerable <TSource> source, FuncNewton <TSource, string> valueSelector, string testValue) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (valueSelector == null) { throw new ArgumentNullException(nameof(valueSelector)); } IEnumerable <TSource> caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return(caseInsensitiveResults.SingleOrDefault()); } else { // multiple results returned. now filter using case sensitivity IEnumerable <TSource> caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return(caseSensitiveResults.SingleOrDefault()); } }