System.Type.GetGenericArguments()

Here are the examples of the csharp api System.Type.GetGenericArguments() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2739 Examples 7

19 Source : EnumValueRetrieverAndComparer.cs
with MIT License
from ARKlab

private bool _isEnum(Type t)
        {
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
                return typeof(Enum).IsreplacedignableFrom(t.GetGenericArguments()[0]);
            return t.IsEnum;
        }

19 Source : EnumValueRetrieverAndComparer.cs
with MIT License
from ARKlab

private static Type GetTheEnumType(Type enumType)
        {
            return ThisIsNotANullableEnum(enumType) ? enumType : enumType.GetGenericArguments()[0];
        }

19 Source : XlsxOutputFormatter.cs
with MIT License
from ARKlab

private Type _elementType(Type type)
        {
            // Type is Array
            // short-circuit if you expect lots of arrays 
            if (type.IsArray)
                return type.GetElementType();

            // type is IEnumerable<T>;
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return type.GetGenericArguments()[0];

            // type implements/extends IEnumerable<T>;
            var enumType = type.GetInterfaces()
                                    .Where(t => t.IsGenericType &&
                                           t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                                    .Select(t => t.GenericTypeArguments[0]).FirstOrDefault();
            return enumType;
        }

19 Source : ReflectionHelper.cs
with MIT License
from ARKlab

public static Type GetEnumerableItemType(Type type)
        {
            // If the type preplaceded IS the interface type, success!
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return type.GetGenericArguments()[0];

            // Otherwise, loop through the interfaces until we find IEnumerable (if it exists).
            Type[] interfaces = type.GetInterfaces();
            foreach (Type i in interfaces)
            {
                if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    return i.GetGenericArguments()[0];
                }
            }

            return null;
        }

19 Source : GenericDictionaryWithConvertibleKey.cs
with MIT License
from ARKlab

public override bool CanConvert(Type typeToConvert)
        {
            Type actualTypeToConvert;
            Type keyType = null;
            if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClreplaced(typeof(Dictionary<,>))) != null)
            {
                keyType = actualTypeToConvert.GetGenericArguments()[0];
            }
            else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary<,>))) != null)
            {
                keyType = actualTypeToConvert.GetGenericArguments()[0];                
            }
            else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<,>))) != null)
            {
                keyType = actualTypeToConvert.GetGenericArguments()[0];                
            }

            if (keyType != null && keyType != typeof(string))
            {
                var converter = TypeDescriptor.GetConverter(keyType);
                return converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string));
            }

            return false;
        }

19 Source : GenericDictionaryWithConvertibleKey.cs
with MIT License
from ARKlab

public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            Type actualTypeToConvert;
            Type converterType = null;
            if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClreplaced(typeof(Dictionary<,>))) != null)
            {
                var args = actualTypeToConvert.GetGenericArguments();
                var keyType = args[0];
                var elementType = args[1];

                converterType = typeof(DictionaryBaseConverter<,,>)
                    .MakeGenericType(typeToConvert, keyType, elementType);
            }
            else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary<,>))) != null)
            {
                var args = actualTypeToConvert.GetGenericArguments();
                var keyType = args[0];
                var elementType = args[1];

                if (actualTypeToConvert == typeToConvert)
                    converterType = typeof(DictionaryConverter<,>)
                        .MakeGenericType(keyType, elementType);
                else
                    converterType = typeof(IDictionaryBaseConverter<,,>)
                        .MakeGenericType(typeToConvert, keyType, elementType);                
            }
            else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<,>))) != null)
            {
                var args = actualTypeToConvert.GetGenericArguments();
                var keyType = args[0];
                var elementType = args[1];

                converterType = typeof(ReadOnlyDictionaryConverter<,>)
                        .MakeGenericType(keyType, elementType);
            }

            if (converterType != null)
                return (JsonConverter)Activator.CreateInstance(converterType, options);

            return null;
        }

19 Source : FopExpressionBuilder.cs
with MIT License
from arslanaybars

private static FilterDataTypes GetFilterDataTypes(PropertyInfo pi)
        {
            var propertyName = pi.PropertyType.IsGenericType &&
                               pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
                ? pi.PropertyType.GetGenericArguments()[0].Name
                : pi.PropertyType.Name;

            if (pi.PropertyType.IsEnum)
            {
                return FilterDataTypes.Enum;
            }

            if (propertyName == "Int32" ||
                propertyName == "UInt16" ||
                propertyName == "Int16")
            {
                return FilterDataTypes.Int;
            }

            if (propertyName == "Int64" ||
                propertyName == "UInt64")
            {
                return FilterDataTypes.Long;
            }

            if (propertyName == "String")
            {
                return FilterDataTypes.String;
            }

            if (propertyName == "Char")
            {
                return FilterDataTypes.Char;
            }

            if (propertyName == "DateTime")
            {
                return FilterDataTypes.DateTime;
            }

            if (propertyName == "Boolean")
            {
                return FilterDataTypes.Boolean;
            }

            if (propertyName == "Guid")
            {
                return FilterDataTypes.Guid;
            }

            throw new ArgumentOutOfRangeException();
        }

19 Source : ServiceProvider.cs
with Apache License 2.0
from aspnet

private object GetMultiService(Type collectionType)
        {
            if (collectionType.IsGenericType &&
                collectionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                Type serviceType = collectionType.GetGenericArguments().Single();
                Type listType = typeof(List<>).MakeGenericType(serviceType);
                var services = (IList)Activator.CreateInstance(listType);

                Func<object> serviceFactory;
                if (_services.TryGetValue(serviceType, out serviceFactory))
                {
                    services.Add(serviceFactory());

                    List<Func<object>> prior;
                    if (_priorServices.TryGetValue(serviceType, out prior))
                    {
                        foreach (var factory in prior)
                        {
                            services.Add(factory());
                        }
                    }
                }
                return services;
            }
            return null;
        }

19 Source : EventSubscriptionMapper.cs
with Apache License 2.0
from atata-framework

private EventSubscriptionItem CreateSubscription(Type eventHandlerType, Dictionary<string, object> eventHandlerValuesMap)
        {
            Type expectedInterfaceType = typeof(IEventHandler<>);

            Type eventHanderType = eventHandlerType.GetGenericInterfaceType(expectedInterfaceType)
                ?? throw new ConfigurationException(
                    $"\"{nameof(EventSubscriptionJsonSection.HandlerType)}\" configuration property of {eventHandlerType.FullName} type doesn't implement {expectedInterfaceType.FullName}.");

            Type eventType = eventHanderType.GetGenericArguments()[0];

            object eventHandler = _objectCreator.Create(eventHandlerType, eventHandlerValuesMap);

            return new EventSubscriptionItem(eventType, eventHandler);
        }

19 Source : NDesk.Options.cs
with Apache License 2.0
from atifaziz

protected static T Parse<T> (string value, OptionContext c)
		{
			Type tt = typeof (T);
			bool nullable = tt.IsValueType && tt.IsGenericType &&
				!tt.IsGenericTypeDefinition &&
				tt.GetGenericTypeDefinition () == typeof (Nullable<>);
			Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
			TypeConverter conv = TypeDescriptor.GetConverter (targetType);
			T t = default (T);
			try {
				if (value != null)
					t = (T) conv.ConvertFromString (value);
			}
			catch (Exception e) {
				throw new OptionException (
						string.Format (
							c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
							value, targetType.Name, c.OptionName),
						c.OptionName, e);
			}
			return t;
		}

19 Source : Options.cs
with MIT License
from atifaziz

protected static T Parse<T> (string value, OptionContext c)
        {
            Type tt = typeof (T);
            bool nullable = tt.IsValueType && tt.IsGenericType &&
                !tt.IsGenericTypeDefinition &&
                tt.GetGenericTypeDefinition () == typeof (Nullable<>);
            Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
            TypeConverter conv = TypeDescriptor.GetConverter (targetType);
            T t = default (T);
            try {
                if (value != null)
                    t = (T) conv.ConvertFromString (value);
            }
            catch (Exception e) {
                throw new OptionException (
                        string.Format (
                            c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
                            value, targetType.Name, c.OptionName),
                        c.OptionName, e);
            }
            return t;
        }

19 Source : TreeDecomposition.cs
with GNU General Public License v3.0
from audiamus

private void dumpCollection (object o, Stack<Type> stack, Type objectType, TextWriter tw, Indent ind, 
      EDumpFlags flags, string itemCaption, CustomFormat itemFormat
    ) {

      // item type
      Type itemType = objectType.GetInterfaces ()
        .Where (t => t.IsGenericType && t.GetGenericTypeDefinition ().Equals (typeof (IEnumerable<>)))
          .Select (t => t.GetGenericArguments ()[0])
            .FirstOrDefault () ?? typeof (object);
      string desc = getTypeDesc (itemType, flags, true);
      //if (!desc.IsNull())
      //  ; // for debug

      bool isPrimitive = isPrimitiveType (itemType);

      if (flags.HasFlag (EDumpFlags.withItmCnt)) {
        if (itemCaption.IsNullOrWhiteSpace ()) {
          if (isPrimitive)
            itemCaption = "#";
          else
            itemCaption = itemType.Name + " ";
        } else
          itemCaption += " ";
      } else if (itemCaption.IsNullOrWhiteSpace () && !isPrimitive)
        itemCaption = itemType.Name;

      int i = 0;
      // hard cast
      foreach (var item in (IEnumerable)o) {
        i++;
        string caption;
        if (flags.HasFlag (EDumpFlags.withItmCnt))
          caption = $"{itemCaption}{i}";
        else
          caption = itemCaption;

        if (isPrimitive)

          //  this level, as primitive
          write (tw, ind, caption, item, itemFormat, desc, flags.HasFlag(EDumpFlags.descOnTop));

        else

          //  deeper level, recursive call
          dump (item, stack, tw, ind, flags, caption, itemCaption, itemFormat, desc, true);

      }
    }

19 Source : VisitorExtensions.cs
with MIT License
from AutoMapper

public static List<Type> GetUnderlyingGenericTypes(this Type type) => 
            type == null || !type.GetTypeInfo().IsGenericType
            ? new List<Type>()
            : type.GetGenericArguments().ToList();

19 Source : ExpressionMapper.cs
with MIT License
from AutoMapper

private static void UpdateToNonNullableExpression(Expression right, out Expression newRight)
            {
                if (right is ConstantExpression expression)
                {
                    var t = right.Type.IsNullableType()
                        ? right.Type.GetGenericArguments()[0]
                        : right.Type;
                    newRight = Constant(expression.Value, t);
                }
                else if (right is UnaryExpression)
                    newRight = ((UnaryExpression) right).Operand;
                else
                    throw new AutoMapperMappingException(
                        "Mapping a BinaryExpression where one side is nullable and the other isn't");
            }

19 Source : MapperExtensions.cs
with MIT License
from AutoMapper

private static TDestDelegate MapExpression<TDestDelegate>(this IMapper mapper, 
            LambdaExpression expression, 
            Func<IConfigurationProvider, Dictionary<Type, Type>, XpressionMapperVisitor> getVisitor, 
            Func<Type, bool> shouldConvertMappedBodyToDestType)
            where TDestDelegate : LambdaExpression
        {
            return MapExpression<TDestDelegate>
            (
                mapper.ConfigurationProvider,
                expression,
                expression.GetType().GetGenericArguments()[0],
                typeof(TDestDelegate).GetGenericArguments()[0],
                getVisitor,
                shouldConvertMappedBodyToDestType
            );
        }

19 Source : MapperExtensions.cs
with MIT License
from AutoMapper

private static TDestDelegate MapExpression<TDestDelegate>(IConfigurationProvider configurationProvider,
            LambdaExpression expression,
            Type typeSourceFunc,
            Type typeDestFunc,
            Func<IConfigurationProvider, Dictionary<Type, Type>, XpressionMapperVisitor> getVisitor,
            Func<Type, bool> shouldConvertMappedBodyToDestType)
            where TDestDelegate : LambdaExpression
        {
            return CreateVisitor(new Dictionary<Type, Type>().AddTypeMappingsFromDelegates(configurationProvider, typeSourceFunc, typeDestFunc));

            TDestDelegate CreateVisitor(Dictionary<Type, Type> typeMappings)
                => MapBody(typeMappings, getVisitor(configurationProvider, typeMappings));

            TDestDelegate MapBody(Dictionary<Type, Type> typeMappings, XpressionMapperVisitor visitor)
                => GetLambda(typeMappings, visitor, visitor.Visit(expression.Body));

            TDestDelegate GetLambda(Dictionary<Type, Type> typeMappings, XpressionMapperVisitor visitor, Expression mappedBody)
            {
                if (mappedBody == null)
                    throw new InvalidOperationException(Resource.cantRemapExpression);

                return (TDestDelegate)Lambda
                (
                    typeDestFunc,
                    ConvertBody(),
                    expression.GetDestinationParameterExpressions(visitor.InfoDictionary, typeMappings)
                );

                Expression ConvertBody()
                {
                    if (!shouldConvertMappedBodyToDestType(typeDestFunc))
                        return mappedBody;

                    mappedBody = mappedBody.GetUnconvertedExpression();

                    return ElementTypeHelper.ToType(mappedBody, typeDestFunc.GetGenericArguments().Last());
                }
            }
        }

19 Source : MapperExtensions.cs
with MIT License
from AutoMapper

public static Dictionary<Type, Type> AddTypeMapping(this Dictionary<Type, Type> typeMappings, IConfigurationProvider configurationProvider, Type sourceType, Type destType)
        {
            if (typeMappings == null)
                throw new ArgumentException(Resource.typeMappingsDictionaryIsNull);

            if (sourceType.GetTypeInfo().IsGenericType && sourceType.GetGenericTypeDefinition() == typeof(Expression<>))
            {
                sourceType = sourceType.GetGenericArguments()[0];
                destType = destType.GetGenericArguments()[0];
            }

            if (!typeMappings.ContainsKey(sourceType) && sourceType != destType)
            {
                typeMappings.Add(sourceType, destType);
                if (typeof(Delegate).IsreplacedignableFrom(sourceType))
                    typeMappings.AddTypeMappingsFromDelegates(configurationProvider, sourceType, destType);
                else
                {
                    typeMappings.AddUnderlyingTypes(configurationProvider, sourceType, destType);
                    typeMappings.FindChildPropertyTypeMaps(configurationProvider, sourceType, destType);
                    typeMappings.AddIncludedTypeMaps(configurationProvider, sourceType, destType);
                }
            }

            return typeMappings;
        }

19 Source : MapperExtensions.cs
with MIT License
from AutoMapper

public static Type ReplaceType(this Dictionary<Type, Type> typeMappings, Type sourceType)
        {
            if (!sourceType.IsGenericType)
            {
                return typeMappings.TryGetValue(sourceType, out Type destType) ? destType : sourceType;
            }
            else
            {
                if (typeMappings.TryGetValue(sourceType, out Type destType))
                    return destType;
                else
                    return sourceType.GetGenericTypeDefinition().MakeGenericType
                    (
                        sourceType
                        .GetGenericArguments()
                        .Select(type => typeMappings.ReplaceType(type))
                        .ToArray()
                    );
            }
        }

19 Source : MapperExtensions.cs
with MIT License
from AutoMapper

private static Dictionary<Type, Type> AddTypeMappingsFromDelegates(this Dictionary<Type, Type> typeMappings, IConfigurationProvider configurationProvider, Type sourceType, Type destType)
        {
            if (typeMappings == null)
                throw new ArgumentException(Resource.typeMappingsDictionaryIsNull);

            typeMappings.DoAddTypeMappingsFromDelegates
            (
                configurationProvider,
                sourceType.GetGenericArguments().ToList(),
                destType.GetGenericArguments().ToList()
            );

            return typeMappings;
        }

19 Source : ImmutableArray.cs
with MIT License
from AutoReviser

public static object[] ToArray(object instance)
        {
            Type[] typeArguments = instance.GetType().GetGenericArguments();

            MethodInfo method = typeof(Enumerable)
                .GetMethod("ToArray")
                .MakeGenericMethod(typeArguments);

            object array = method.Invoke(obj: default, new[] { instance });

            return typeArguments[0].IsValueType
                ? ((IEnumerable)array).Cast<object>().ToArray()
                : (object[])array;
        }

19 Source : ImmutableArray.cs
with MIT License
from AutoReviser

public static TImmutableArray Create<TImmutableArray>(object[] elements)
        {
            Type[] typeArguments = new[]
            {
                typeof(TImmutableArray),
                typeof(TImmutableArray).GetGenericArguments()[0],
            };

            return (TImmutableArray)typeof(ImmutableArray)
                .GetMethod(nameof(Factory), Static | NonPublic)
                .MakeGenericMethod(typeArguments)
                .Invoke(obj: default, new[] { elements });
        }

19 Source : ComplexTypeReflector.cs
with MIT License
from Avanade

private static Type? GetCollectionType(Type type)
        {
            var t = type.GetInterfaces().FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>));
            if (t == null)
                return null;

            return ((t == typeof(ICollection<>)) ? type : t).GetGenericArguments()[0];
        }

19 Source : ComplexTypeReflector.cs
with MIT License
from Avanade

private static Type? GetEnumerableType(Type type)
        {
            var t = type.GetInterfaces().FirstOrDefault(x => (x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>)));
            if (t == null)
            {
                t = type.GetInterfaces().FirstOrDefault(x => x == typeof(IEnumerable));
                if (t == null)
                    return null;
            }

            var gas = ((t == typeof(IEnumerable)) ? type : t).GetGenericArguments();
            if (gas.Length == 0)
                return null;

            if (type == typeof(IEnumerable<>).MakeGenericType(new Type[] { gas[0] }))
                return gas[0];

            return null;
        }

19 Source : ComplexTypeReflector.cs
with MIT License
from Avanade

internal static (Type?, Type?) GetDictionaryType(Type type)
        {
            var t = type.GetInterfaces().FirstOrDefault(x => (x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)));
            if (t == null)
                return (null, null);

            var gas = t.GetGenericArguments();
            if (gas.Length != 2)
                return (null, null);

            return (gas[0], gas[1]);
        }

19 Source : ReflectionUtil.cs
with MIT License
from AVPolyakov

private static PropertyInfo ResolveProperty(MethodInfo methodInfo, int metadataToken)
        {
            var methodBase = methodInfo.Module.ResolveMethod(metadataToken,
                methodInfo.DeclaringType.GetGenericArguments(), null);
            if (!propertyDictionaryByGetMethod.TryGetValue(methodBase.DeclaringType, out var infos))
            {
                infos = methodBase.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                    .ToDictionary(_ => {
                        MethodBase method = _.GetGetMethod(true);
                        return method;
                    });
                propertyDictionaryByGetMethod.TryAdd(methodBase.DeclaringType, infos);
            }
            var propertyInfo = infos[methodBase];
            propertyDictionary.TryAdd(methodInfo, propertyInfo);
            return propertyInfo;
        }

19 Source : ReflectionUtil.cs
with MIT License
from AVPolyakov

private static MemberInfo ResolveField(MethodInfo methodInfo, int metadataToken)
        {
            var fieldInfo = methodInfo.Module.ResolveField(metadataToken,
                methodInfo.DeclaringType.GetGenericArguments(), null);
            fieldDictionary.TryAdd(methodInfo, fieldInfo);
            return fieldInfo;
        }

19 Source : Extensions.cs
with Apache License 2.0
from aws

public static string GetTypeFullCodeName(this Type t)
        {
            if (!t.IsGenericType)
            {
                return t.Name;
            }
            string typeName = t.GetGenericTypeDefinition().Name;

            typeName = typeName.Substring(0, typeName.IndexOf('`'));
            string args = string.Join(",", t.GetGenericArguments().Select(ta => GetTypeFullCodeName(ta)).ToArray());

            return typeName + "<" + args + ">";
        }

19 Source : HelpGeneratorBase.cs
with Apache License 2.0
from aws

public static string GetTypeDisplayName(Type propertyType, bool useFullName, bool stripNullable = true)
        {
            string name;
            if (propertyType.IsGenericParameter)
                name = propertyType.Name;
            else if (propertyType.IsGenericType)
            {
                if (stripNullable && propertyType.FullName.StartsWith("System.Nullable`"))
                {
                    return GetTypeDisplayName(propertyType.GetGenericArguments()[0], useFullName, false);
                }

                var baseName = useFullName ? propertyType.FullName : propertyType.Name;
                var pos = baseName.IndexOf('`');
                baseName = baseName.Substring(0, pos);

                var paramCount = propertyType.GetGenericArguments().Length;

                var pars = new StringBuilder();
                if (propertyType.IsGenericTypeDefinition)
                {
                    if (paramCount == 1)
                        pars.Append("T");
                    else
                    {
                        for (var i = 1; i <= paramCount; i++)
                        {
                            if (pars.Length > 0)
                                pars.Append(", ");

                            pars.AppendFormat("T{0}", i);
                        }
                    }
                }
                else
                {
                    foreach (var t in propertyType.GetGenericArguments())
                    {
                        if (pars.Length > 0)
                            pars.Append(", ");
                        pars.AppendFormat(GetTypeDisplayName(t, useFullName, false));
                    }
                }

                name = string.Format("{0}<{1}>", baseName, pars.ToString());
            }
            else
                name = useFullName ? propertyType.FullName : propertyType.Name;

            if (name == null)
                throw new ApplicationException(string.Format("Failed to resolve display for type {0}", propertyType.ToString()));

            return name;
        }

19 Source : HelpGeneratorBase.cs
with Apache License 2.0
from aws

private string GetValidTypeName(Type type)
        {
            if (type.IsArray)
                return GetValidTypeName(type.GetElementType()) + "[]";
            
            if (type.IsGenericType)
            {
                var genericArguments = type.GetGenericArguments();
                var genericType = type.GetGenericTypeDefinition();

                if (genericType.IsreplacedignableFrom(typeof(List<>)))
                    return string.Format("List<{0}>", GetValidTypeName(genericArguments[0]));
                
                if (genericType.IsreplacedignableFrom(typeof(IEnumerable<>)))
                    return string.Format("IEnumerable<{0}>", GetValidTypeName(genericArguments[0]));
                
                if (genericType.IsreplacedignableFrom(typeof(Dictionary<,>)))
                    return string.Format("Dictionary<{0}, {1}>", GetValidTypeName(genericArguments[0]), GetValidTypeName(genericArguments[1]));
                
                if (string.Equals(genericType.FullName, "Amazon.S3.Model.Tuple`2", StringComparison.Ordinal))
                    return string.Format("Tuple<{0}, {1}>", GetValidTypeName(genericArguments[0]), GetValidTypeName(genericArguments[1]));

                if (genericType.IsreplacedignableFrom(typeof(Nullable<>)))
                    return string.Format("{0}", GetValidTypeName(genericArguments[0]));

                Logger.LogError("Can't determine generic type. Type = [{0}], GenericType = [{1}]", type.FullName, genericType.FullName);
                return null;
            }

            return type.Namespace + "." + type.Name;
        }

19 Source : BaseCmdlets.cs
with Apache License 2.0
from aws

protected static Func<TResponse, TCmdlet, object> CreateSelectDelegate<TResponse, TCmdlet>(string selectString) where TCmdlet : BaseCmdlet
        {
            switch(selectString)
            {
                case null:
                case "":
                    return null;
                case "*":
                    return (response, cmdlet) => response;
                case var s when s.StartsWith("^"):
                {
                    var type = typeof(TCmdlet);
                    var parameterName = selectString.Substring(1);

                    PropertyInfo selectedProperty = null;
                    foreach (var property in type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (property.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase))
                        {
                            selectedProperty = property;
                            break;
                        }
                        else
                        {
                            foreach (var attributeAlias in property
                                .GetCustomAttributes(typeof(AliasAttribute), false)
                                .Cast<AliasAttribute>()
                                .SelectMany(attribute => attribute.AliasNames))
                            {
                                if (attributeAlias.Equals(parameterName, StringComparison.OrdinalIgnoreCase))
                                {
                                    selectedProperty = property;
                                    break;
                                }
                            }
                            if (selectedProperty != null)
                            {
                                break;
                            }
                        }
                    }
                    var getter = selectedProperty?.GetGetMethod();
                    if (getter == null)
                    {
                        return null;
                    }
                    return (response, cmdlet) => getter.Invoke(cmdlet, EmptyObjectArray);
                }
                default:
                {
                    var type = typeof(TResponse);
                    var selectors = new List<Func<IEnumerable<object>, IEnumerable<object>>>();
                    foreach (var propertyName in selectString.Split('.'))
                    {
                        var properties = type
                            .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                            .Where(property => property.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
                            .ToArray();
                        if (properties.Length != 1)
                        {
                            return null;
                        }
                        var getter = properties[0].GetGetMethod();
                        if (getter == null)
                        {
                            return null;
                        }
                        type = properties[0].PropertyType;
                        var iEnumerableInterface = type.GetInterface("System.Collections.Generic.IEnumerable`1");
                        if (iEnumerableInterface != null && type != typeof(string))
                        {
                            selectors.Add(enumerable => enumerable
                                .Select(item => ((IEnumerable)getter.Invoke(item, EmptyObjectArray)).Cast<object>())
                                .Where(collection => collection != null)
                                .SelectMany(collection => collection)
                                .Where(item => item != null));
                            type = iEnumerableInterface.GetGenericArguments()[0];
                        }
                        else
                        {
                            selectors.Add(enumerable => enumerable
                                .Select(item => getter.Invoke(item, EmptyObjectArray))
                                .Where(item => item != null));
                        }
                    }
                    return (response, cmdlet) =>
                    {
                        if (response == null)
                        {
                            return null;
                        }
                        IEnumerable<object> current = new object[] { response };
                        foreach (var selector in selectors)
                        {
                            current = selector(current);
                        }
                        return current.ToArray();
                    };
                }
            }
        }

19 Source : Extensions.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static Type GetFirstGenericArgument (this Type self)
		{
			return self.GetGenericArguments () [0];
		}

19 Source : Extensions.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static Type MakeGenericTypeFrom (this Type self, Type type)
		{
			return self.MakeGenericType (type.GetGenericArguments ());
		}

19 Source : Math.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static object Evaluate (object a, object b, Type t, ExpressionType et)
		{
			TypeCode tc = Type.GetTypeCode (t);
			if (tc == TypeCode.Object) {
				if (!t.IsNullable ()) {
					throw new NotImplementedException (
						string.Format (
						"Expression with Node type {0} for type {1}",
						t.FullName,
						tc));

				}
				return EvaluateNullable (a, b, Type.GetTypeCode (t.GetGenericArguments () [0]), et);
			}
			return Evaluate (a, b, tc, et);
		}

19 Source : SqlMapperExtensions.cs
with MIT License
from ay2015

public static long Insert<T>(this IDbConnection connection, T enreplacedyToInsert, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
		{
			bool flag = false;
			Type type = typeof(T);
			if (type.IsArray)
			{
				flag = true;
				type = type.GetElementType();
			}
			else if (type.IsGenericType())
			{
				flag = true;
				type = type.GetGenericArguments()[0];
			}
			string tableName = GetTableName(type);
			StringBuilder stringBuilder = new StringBuilder(null);
			List<PropertyInfo> first = TypePropertiesCache(type);
			List<PropertyInfo> list = KeyPropertiesCache(type);
			List<PropertyInfo> second = ComputedPropertiesCache(type);
			List<PropertyInfo> list2 = first.Except(list.Union(second)).ToList();
			ISqlAdapter formatter = GetFormatter(connection);
			for (int i = 0; i < list2.Count; i++)
			{
				PropertyInfo propertyInfo = list2.ElementAt(i);
				formatter.AppendColumnName(stringBuilder, propertyInfo.Name);
				if (i < list2.Count - 1)
				{
					stringBuilder.Append(", ");
				}
			}
			StringBuilder stringBuilder2 = new StringBuilder(null);
			for (int j = 0; j < list2.Count; j++)
			{
				PropertyInfo propertyInfo2 = list2.ElementAt(j);
				stringBuilder2.AppendFormat("@{0}", propertyInfo2.Name);
				if (j < list2.Count - 1)
				{
					stringBuilder2.Append(", ");
				}
			}
			bool num = connection.State == ConnectionState.Closed;
			if (num)
			{
				connection.Open();
			}
			int num2;
			if (!flag)
			{
				num2 = formatter.Insert(connection, transaction, commandTimeout, tableName, stringBuilder.ToString(), stringBuilder2.ToString(), list, enreplacedyToInsert);
			}
			else
			{
				string text = string.Format("insert into {0} ({1}) values ({2})", tableName, stringBuilder, stringBuilder2);
				num2 = SqlMapper.Execute(connection, text, (object)enreplacedyToInsert, transaction, commandTimeout, (CommandType?)null);
			}
			if (num)
			{
				connection.Close();
			}
			return num2;
		}

19 Source : SqlMapperExtensions.cs
with MIT License
from ay2015

public static bool Delete<T>(this IDbConnection connection, T enreplacedyToDelete, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
		{
			if (enreplacedyToDelete == null)
			{
				throw new ArgumentException("Cannot Delete null Object", "enreplacedyToDelete");
			}
			Type type = typeof(T);
			if (type.IsArray)
			{
				type = type.GetElementType();
			}
			else if (type.IsGenericType())
			{
				type = type.GetGenericArguments()[0];
			}
			List<PropertyInfo> list = KeyPropertiesCache(type).ToList();
			List<PropertyInfo> list2 = ExplicitKeyPropertiesCache(type);
			if (!list.Any() && !list2.Any())
			{
				throw new ArgumentException("Enreplacedy must have at least one [Key] or [ExplicitKey] property");
			}
			string tableName = GetTableName(type);
			list.AddRange(list2);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("delete from {0} where ", tableName);
			ISqlAdapter formatter = GetFormatter(connection);
			for (int i = 0; i < list.Count; i++)
			{
				PropertyInfo propertyInfo = list.ElementAt(i);
				formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo.Name);
				if (i < list.Count - 1)
				{
					stringBuilder.AppendFormat(" and ");
				}
			}
			return SqlMapper.Execute(connection, stringBuilder.ToString(), (object)enreplacedyToDelete, transaction, commandTimeout, (CommandType?)null) > 0;
		}

19 Source : SqlMapperExtensions.cs
with MIT License
from ay2015

public static bool Update<T>(this IDbConnection connection, T enreplacedyToUpdate, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
		{
			IProxy proxy = enreplacedyToUpdate as IProxy;
			if (proxy != null && !proxy.IsDirty)
			{
				return false;
			}
			Type type = typeof(T);
			if (type.IsArray)
			{
				type = type.GetElementType();
			}
			else if (type.IsGenericType())
			{
				type = type.GetGenericArguments()[0];
			}
			List<PropertyInfo> list = KeyPropertiesCache(type).ToList();
			List<PropertyInfo> list2 = ExplicitKeyPropertiesCache(type);
			if (!list.Any() && !list2.Any())
			{
				throw new ArgumentException("Enreplacedy must have at least one [Key] or [ExplicitKey] property");
			}
			string tableName = GetTableName(type);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("update {0} set ", tableName);
			List<PropertyInfo> first = TypePropertiesCache(type);
			list.AddRange(list2);
			List<PropertyInfo> second = ComputedPropertiesCache(type);
			List<PropertyInfo> list3 = first.Except(list.Union(second)).ToList();
			ISqlAdapter formatter = GetFormatter(connection);
			for (int i = 0; i < list3.Count; i++)
			{
				PropertyInfo propertyInfo = list3.ElementAt(i);
				formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo.Name);
				if (i < list3.Count - 1)
				{
					stringBuilder.AppendFormat(", ");
				}
			}
			stringBuilder.Append(" where ");
			for (int j = 0; j < list.Count; j++)
			{
				PropertyInfo propertyInfo2 = list.ElementAt(j);
				formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo2.Name);
				if (j < list.Count - 1)
				{
					stringBuilder.AppendFormat(" and ");
				}
			}
			return SqlMapper.Execute(connection, stringBuilder.ToString(), (object)enreplacedyToUpdate, transaction, commandTimeout, (CommandType?)null) > 0;
		}

19 Source : Class1.cs
with MIT License
from aykutsahin98

protected override void OnBefore(IInvocation invocation)
        {
            var validator = (IValidator)Activator.CreateInstance(_validatorType);//reflection
            var enreplacedyType = _validatorType.BaseType.GetGenericArguments()[0];
            var enreplacedies = invocation.Arguments.Where(t => t.GetType() == enreplacedyType);
            foreach (var enreplacedy in enreplacedies)
            {
                ValidationTool.Validate(validator, enreplacedy);
            }
        }

19 Source : JSONMappings.cs
with MIT License
from azist

public static string MapCLRTypeToJSON(Type type, out bool isNullable)
    {
      isNullable = false;
      if (type == null) return JTP_OBJECT;

      if (typeof(string).IsreplacedignableFrom(type))
      {
        return JTP_STRING;
      }

      if (typeof(Doc).IsreplacedignableFrom(type))
      {
        return JTP_OBJECT;
      }

      if (typeof(IDictionary).IsreplacedignableFrom(type))
      {
        return JTP_MAP;
      }

      if (typeof(IEnumerable).IsreplacedignableFrom(type))
      {
        return JTP_ARRAY;
      }

      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
      {
        isNullable = true;
        type = type.GetGenericArguments()[0];
      }

      //dictionary lookup
      if (!s_CLR.TryGetValue(type, out string name))
        name = JTP_OBJECT;

      return name;
    }

19 Source : Schema.FieldDef.cs
with MIT License
from azist

private void ctor(string name, int order, Type type, IEnumerable<FieldAttribute> attrs, PropertyInfo memberInfo = null)
      {
        if (name.IsNullOrWhiteSpace() || type == null || attrs == null)
          throw new DataException(StringConsts.ARGUMENT_ERROR + "FieldDef.ctor(..null..)");

        m_Name = name;
        m_Order = order;
        m_Type = type;
        m_GetOnly = memberInfo != null && !memberInfo.CanWrite;
        m_Attrs = new List<FieldAttribute>(attrs);
        m_TargetAttrsCache = new FiniteSetLookup<string, FieldAttribute>(findFieldAttributeFor, StringComparer.InvariantCultureIgnoreCase);

        if (m_Attrs.Count < 1)
          throw new DataException(StringConsts.CRUD_FIELDDEF_ATTR_MISSING_ERROR.Args(name));

        //add ANY_TARGET attribute
        if (!m_Attrs.Any(a => a.TargetName == TargetedAttribute.ANY_TARGET))
        {
          var isAnyKey = m_Attrs.Any(a => a.Key);
          var ata = new FieldAttribute(FieldAttribute.ANY_TARGET, key: isAnyKey);
          m_Attrs.Add(ata);
        }

        m_Attrs.ForEach(a => a.Seal());

        //Set and compile setter
        if (memberInfo != null)
        {
          m_MemberInfo = memberInfo;
          if (!m_GetOnly)//if it has a setter
          {
            m_MemberSet = makeSetterLambda(memberInfo);
          }
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
          m_NonNullableType = type.GetGenericArguments()[0];
        else
          m_NonNullableType = type;

        m_AnyTargetKey = this[null].Key;
      }

19 Source : StringValueConversion.cs
with MIT License
from azist

public static object AsType(this string val, Type tp, bool strict = true)
    {
      try
      {
        if (s_CONV.TryGetValue(tp, out Func<string, bool, object> func)) return func(val, strict);

        if (tp.IsEnum)
        {
          return Enum.Parse(tp, val, true);
        }

        if (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
          var v = val;
          if (string.IsNullOrWhiteSpace(v)) return null;


          var gargs = tp.GetGenericArguments();
          if (gargs.Length == 1)
          {
            var gtp = gargs[0];
            if (gtp.IsEnum)
            {
              return Enum.Parse(gtp, v, true);
            }
          }
        }
      }
      catch (Exception error)
      {
        throw new AzosException(string.Format(StringConsts.STRING_VALUE_COULD_NOT_BE_GOTTEN_AS_TYPE_ERROR,
                                              val ?? CoreConsts.NULL_STRING, tp.FullName), error);
      }

      throw new AzosException(string.Format(StringConsts.STRING_VALUE_COULD_NOT_BE_GOTTEN_AS_TYPE_ERROR,
                                              val ?? CoreConsts.NULL_STRING, tp.FullName));
    }

19 Source : DataDocConverter.cs
with MIT License
from azist

protected virtual bool TryConvertBSONtoCLR(Type target, BSONElement element, string targetName, out object clrValue, Func<BSONDoreplacedent, BSONElement, bool> filter)
        {
          if (element==null || element is BSONNullElement)
          {
            clrValue = null;
            return true;
          }

          if (target == typeof(object))
          {
            //just unwrap Bson:CLR = 1:1, without type conversion
            clrValue = DirectConvertBSONValue( element, filter );
            return true;
          }

          clrValue = null;

          if (target.IsSubclreplacedOf(typeof(TypedDoc)))
          {
            var bsonDoreplacedentElement = element as BSONDoreplacedentElement;
            var doc = bsonDoreplacedentElement != null ? bsonDoreplacedentElement.Value : null;
            if (doc==null) return false;//not doreplacedent
            var tr = (TypedDoc)Activator.CreateInstance(target);
            BSONDoreplacedentToDataDoc(doc, tr, targetName, filter: filter);
            clrValue = tr;
            return true;
          }

          //ARRAY
          if (target.IsArray &&
              target.GetArrayRank()==1 &&
              target!=typeof(byte[]))//exclude byte[] as it is treated with m_BSONtoCLR
          {
            var bsonArrayElement = element as BSONArrayElement;
            var arr = bsonArrayElement != null ? bsonArrayElement.Value : null;
            if (arr==null) return false;//not array
            var telm = target.GetElementType();
            var clrArray = Array.CreateInstance(telm, arr.Length);
            for(var i=0; i<arr.Length; i++)
            {
              object clrElement;
              if (!TryConvertBSONtoCLR(telm, arr[i], targetName, out clrElement, filter))
              {
                return false;//could not convert some element of array
              }
              clrArray.SetValue(clrElement, i);
            }

            clrValue = clrArray;
            return true;
          }

          //LIST<T>
          if (target.IsGenericType && target.GetGenericTypeDefinition() == typeof(List<>))
          {
            var bsonArrayElement = element as BSONArrayElement;
            var arr = bsonArrayElement != null ? bsonArrayElement.Value : null;
            if (arr==null) return false;//not array
            var gargs = target.GetGenericArguments();
            var telm = gargs[0];
            var clrList = Activator.CreateInstance(target) as System.Collections.IList;
            for(var i=0; i<arr.Length; i++)
            {
              object clrElement;
              if (!TryConvertBSONtoCLR(telm, arr[i], targetName, out clrElement, filter))
              {
                return false;//could not convert some element of array into element of List<t>
              }
              clrList.Add( clrElement );
            }

            clrValue = clrList;
            return true;
          }

          //JSONDataMap
          if (target==typeof(JsonDataMap))
          {
            var bsonDoreplacedentElement = element as BSONDoreplacedentElement;
            var doc = bsonDoreplacedentElement != null ? bsonDoreplacedentElement.Value : null;
            clrValue = BSONDoreplacedentToJSONMap(doc, filter);
            return true;
          }

          if (target.IsEnum)
          {
            try
            {
              clrValue = Enum.Parse(target, ((BSONStringElement)element).Value, true);
              return true;
            }
            catch
            {
              return false;
            }
          }

          //Primitive type-targeted value
          Func<BSONElement, object> func;
          if (m_BSONtoCLR.TryGetValue(target, out func))
          {
            try
            {
              clrValue = func(element);
            }
            catch(Exception error)
            {
              Debug.Fail("Error in BSONRowConverter.TryConvertBSONtoCLR(): " + error.ToMessageWithType());
              return false;//functor could not convert
            }
            return true;
          }

          return false;//could not convert
        }

19 Source : CoreUtils.cs
with MIT License
from azist

public static string FullNameWithExpandedGenericArgs(this Type type, bool verbatimPrefix = true)
    {
      var ns = type.Namespace;

      if (verbatimPrefix)
      {
        var nss = ns.Split('.');
        ns = string.Join(".@", nss);
      }


      var gargs = type.GetGenericArguments();

      if (gargs.Length == 0)
      {
        return verbatimPrefix ? "@{0}.{1}".Args(ns, type.FullNestedTypeName(true)) : (type.Namespace + '.' + type.FullNestedTypeName(false));
      }

      var sb = new StringBuilder();

      for (int i = 0; i < gargs.Length; i++)
      {
        if (i > 0) sb.Append(", ");
        sb.Append(gargs[i].FullNameWithExpandedGenericArgs(verbatimPrefix));
      }

      var nm = type.FullNestedTypeName(verbatimPrefix);
      var idx = nm.IndexOf('`');
      if (idx >= 0)
        nm = nm.Substring(0, idx);


      return verbatimPrefix ? "@{0}.{1}<{2}>".Args(ns, nm, sb.ToString()) :
                              "{0}.{1}<{2}>".Args(ns, nm, sb.ToString());
    }

19 Source : CoreUtils.cs
with MIT License
from azist

public static string DisplayNameWithExpandedGenericArgs(this Type type)
    {

      var gargs = type.GetGenericArguments();

      if (gargs.Length == 0)
      {
        return type.Name;
      }

      var sb = new StringBuilder();

      for (int i = 0; i < gargs.Length; i++)
      {
        if (i > 0) sb.Append(", ");
        sb.Append(gargs[i].DisplayNameWithExpandedGenericArgs());
      }

      var nm = type.Name;
      var idx = nm.IndexOf('`');
      if (idx >= 0)
        nm = nm.Substring(0, idx);


      return "{0}<{1}>".Args(nm, sb.ToString());
    }

19 Source : JsonReader.cs
with MIT License
from azist

private static object cast(object v, Type toType, bool fromUI, DocReadOptions options, JsonHandlerAttribute fieldCustomHandler = null)
    {
      //See #264 - the collection inability to cast has no amorphous data so it MUST throw
      //used only for collections inner calls
      if (v==null) return null;

      var customHandler = fieldCustomHandler ?? JsonHandlerAttribute.TryFind(toType);
      if (customHandler != null)
      {
        var castResult = customHandler.TypeCastOnRead(v, toType, fromUI, options);

        if (castResult.Outcome >= JsonHandlerAttribute.TypeCastOutcome.ChangedTargetType) toType = castResult.ToType;

        if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.ChangedSourceValue) v = castResult.Value;
        else if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.HandledCast) return castResult.Value;
      }

      //object goes as is
      if (toType == typeof(object)) return v;

      //IJSONDataObject
      if (toType == typeof(IJsonDataObject))
      {
        if (v is IJsonDataObject) return v;//goes as is
        if (v is string s)//string containing embedded JSON
        {
          var jo = s.JsonToDataObject();
          return jo;
        }
      }

      //IJSONDataMap
      if (toType == typeof(JsonDataMap))
      {
        if (v is JsonDataMap) return v;//goes as is
        if (v is string s)//string containing embedded JSON
        {
          var jo = s.JsonToDataObject() as JsonDataMap;
          return jo;
        }
      }

      //IJSONDataArray
      if (toType == typeof(JsonDataArray))
      {
        if (v is JsonDataArray) return v;//goes as is
        if (v is string s)//string containing embedded JSON
        {
          var jo = s.JsonToDataObject() as JsonDataArray;
          return jo;
        }
      }

      var nntp = toType;
      if (nntp.IsGenericType && nntp.GetGenericTypeDefinition() == typeof(Nullable<>))
        nntp = toType.GetGenericArguments()[0];

      //20191217 DKh
      if (nntp==typeof(DateTime))
      {
        if (options.LocalDates)
        {
          var d = v.AsDateTime(System.Globalization.DateTimeStyles.replacedumeLocal);
          return d;
        }
        else //UTC (the default)
        {
          var d = v.AsDateTime(System.Globalization.DateTimeStyles.replacedumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal);
          return d;
        }
      }
      //20191217 DKh


      //Custom JSON Readable (including config)
      if (typeof(IJsonReadable).IsreplacedignableFrom(nntp) || typeof(IConfigSectionNode).IsreplacedignableFrom(nntp))
      {
        var toAllocate = nntp;

        //Configuration requires special handling because nodes do not exist as independent enreplacedies and there
        //is master/detail relationship between them
        if (toAllocate == typeof(Configuration) ||
            toAllocate == typeof(ConfigSectionNode) ||
            toAllocate == typeof(IConfigSectionNode)) toAllocate = typeof(MemoryConfiguration);

        if (toAllocate.IsAbstract)
          throw new JSONDeserializationException(StringConsts.JSON_DESERIALIZATION_ABSTRACT_TYPE_ERROR.Args(toAllocate.Name, nameof(JsonHandlerAttribute)));

        var newval = SerializationUtils.MakeNewObjectInstance(toAllocate) as IJsonReadable;
        var got = newval.ReadAsJson(v, fromUI, options);//this may re-allocate the result based of newval

        if (!got.match) return null;

        if (typeof(IConfigSectionNode).IsreplacedignableFrom(nntp)) return (got.self as Configuration)?.Root;

        return got.self;
      }

      //byte[] direct replacedignment w/o copies
      if (nntp == typeof(byte[]))
      {
        if (v is byte[] preplaceded) return preplaceded;
        //20210717 - #514
        if (v is string str && str.IsNotNullOrWhiteSpace())
        {
          var buff = str.TryFromWebSafeBase64();
          if (buff != null) return buff;
        }
      }


      //field def = []
      if (toType.IsArray)
      {
        var fvseq = v as IEnumerable;
        if (fvseq == null) return null;//can not set non enumerable into array

        var arr = fvseq.Cast<object>().Select(e => cast(e, toType.GetElementType(), fromUI, options, fieldCustomHandler)).ToArray();
        var newval = Array.CreateInstance(toType.GetElementType(), arr.Length);
        for(var i=0; i<newval.Length; i++)
          newval.SetValue(arr[i], i);

        return newval;
      }

      //field def = List<t>
      if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(List<>))
      {
        var fvseq = v as IEnumerable;
        if (fvseq == null) return false;//can not set non enumerable into List<t>

        var arr = fvseq.Cast<object>().Select(e => cast(e, toType.GetGenericArguments()[0], fromUI, options, fieldCustomHandler)).ToArray();
        var newval = SerializationUtils.MakeNewObjectInstance(toType) as IList;
        for (var i = 0; i < arr.Length; i++)
          newval.Add(arr[i]);

        return newval;
      }

      //last resort
      try
      {
        return StringValueConversion.AsType(v.ToString(), toType, false);
      }
      catch
      {
        return null;//the value could not be converted, and is going to go into amorphous bag if it is enabled
      }
    }

19 Source : ApiDocGenerator.cs
with MIT License
from azist

public string AddTypeToDescribe(Type type, object instance = null)
    {
      if (type == typeof(object)) return "object";
      if (type == typeof(string)) return "string";
      if (type == typeof(decimal)) return "decimal";
      if (type == typeof(DateTime)) return "datetime";
      if (type == typeof(TimeSpan)) return "timespan";
      if (type == typeof(GDID)) return "gdid";
      if (type == typeof(Atom)) return "atom";
      if (type == typeof(Guid)) return "gdid";
      if (type.IsPrimitive) return "{0}".Args(type.Name.ToLowerInvariant());
      if (type.IsArray) return "array({0})".Args(AddTypeToDescribe(type.GetElementType()));
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) return "nullable({0})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]));
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) return "array({0})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]));

      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
        return "map({0},{1})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]), AddTypeToDescribe(type.GetGenericArguments()[1]));

      if (IgnoreTypePatterns.Any(ignore => type.FullName.MatchPattern(ignore))) return DetailLevel > MetadataDetailLevel.Public ? type.Name : "sys";

      instanceList list;
      if (!m_TypesToDescribe.TryGetValue(type, out list))
      {
        list = new instanceList("@{0:x2}-{1}".Args(m_TypesToDescribe.Count, MetadataUtils.GetMetadataTokenId(type)));
        list.Add((null, false));//always at index #0
        m_TypesToDescribe.Add(type, list);
      }

      var idx = list.FindIndex( litem => object.ReferenceEquals(litem.item, instance));
      if (idx < 0)
      {
        list.Add((instance, false));
        idx = list.Count-1;
      }

      return "{0}:{1}".Args(list.ID, idx);
    }

19 Source : DocumentFeedResponse.cs
with MIT License
from Azure

public override DynamicMetaObject BindConvert(ConvertBinder binder)
            {
                Type baseFeedType = typeof(DoreplacedentFeedResponse<bool>).GetGenericTypeDefinition();

                if (binder.Type != typeof(IEnumerable) && (!binder.Type.IsGenericType() || (binder.Type.GetGenericTypeDefinition() != baseFeedType &&
                    binder.Type.GetGenericTypeDefinition() != typeof(IEnumerable<string>).GetGenericTypeDefinition() &&
                    binder.Type.GetGenericTypeDefinition() != typeof(IQueryable<string>).GetGenericTypeDefinition())))
                {
                    return base.BindConvert(binder); //We allow cast only to IResourceFeed<>
                }

                // Setup the 'this' reference
                Expression self = Expression.Convert(this.Expression, this.LimitType);

                MethodCallExpression methodExpression = Expression.Call(
                    typeof(FeedResponseBinder).GetMethod("Convert",
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(
                    binder.Type.GetGenericArguments()[0]),
                    self);

                //Create a meta object to invoke AsType later.
                DynamicMetaObject castOperator = new DynamicMetaObject(
                    methodExpression,
                    BindingRestrictions.GetTypeRestriction(this.Expression, this.LimitType));

                return castOperator;
            }

19 Source : CustomSerializer.cs
with MIT License
from Bannerlord-Coop-Team

private bool IsCollectionSerializableRecursive(Type type)
        {

            List<Type> elementTypes = new List<Type>(type.GetGenericArguments());

            // Native arrays do not have generic arguments
            if (elementTypes.Count == 0 && type.IsArray)
            {
                elementTypes.Add(type.GetElementType());
            }

            // Return true if list is empty, but never should be empty
            // TODO add validate to result or change to false
            bool result = true;
            foreach(Type elementType in elementTypes)
            {
                if (elementType.GetInterface(nameof(ICollection)) != null)
                {
                    result &= IsCollectionSerializableRecursive(elementType);
                }
                else
                {
                    return elementType.IsSerializable;
                }
            }
            return result;
        }

19 Source : ValueMapper.cs
with MIT License
from barnardos-au

public static T MapValue<T>(object cypherValue)
        {
            var targetType = typeof(T);

            if (typeof(IEnumerable).IsreplacedignableFrom(targetType))
            {
                if (!(cypherValue is IEnumerable enumerable))
                    throw new InvalidOperationException($"The cypher value is not a list and cannot be mapped to target type: {targetType.UnderlyingSystemType}");

                if (targetType == typeof(string))
                {
                    return enumerable.As<T>();
                }

                var elementType = targetType.GetGenericArguments()[0];
                var genericType = typeof(CollectionMapper<>).MakeGenericType(elementType);
                var collectionMapper = (ICollectionMapper)genericType.CreateInstance();
                
                return (T)collectionMapper.MapValues(enumerable, targetType);
            }

            if (cypherValue is INode node)
            {
                var enreplacedy = node.Properties.FromObjectDictionary<T>();
                EnreplacedyAccessor.SetNodeId(enreplacedy, node.Id);

                return enreplacedy;
            }

            if (cypherValue is IRelationship relationship)
            {
                var enreplacedy = relationship.Properties.FromObjectDictionary<T>();

                return enreplacedy;
            }

            if (cypherValue is IReadOnlyDictionary<string, object> map)
            {
                return map.FromObjectDictionary<T>();
            }

            if (cypherValue is IEnumerable)
                throw new InvalidOperationException($"The cypher value is a list and cannot be mapped to target type: {targetType.UnderlyingSystemType}");

            return cypherValue.As<T>();
        }

19 Source : TypeStringifier.cs
with MIT License
from bartoszlenar

public static string GetFriendlyName(this Type type, bool includeNamespace = false)
        {
            var typeName = type.Name;

            if (type.IsGenericType)
            {
                var name = type.Name.Substring(0, type.Name.IndexOf('`'));
                var types = string.Join(",", type.GetGenericArguments().Select(t => t.GetFriendlyName(includeNamespace)));

                typeName = $"{name}<{types}>";
            }

            return includeNamespace
                ? $"{type.Namespace}.{typeName}"
                : typeName;
        }

19 Source : ValidatorFactory.cs
with MIT License
from bartoszlenar

public IReadOnlyList<HolderInfo> FetchHolders(params replacedembly[] replacedemblies)
        {
            ThrowHelper.NullArgument(replacedemblies, nameof(replacedemblies));
            ThrowHelper.NullInCollection(replacedemblies, nameof(replacedemblies));

            if (replacedemblies.Length == 0)
            {
                throw new ArgumentException("replacedembly collection must not be empty", nameof(replacedemblies));
            }

            var holders = new List<HolderInfo>();

            var holderTypes = replacedemblies.SelectMany(GetAllSpecificationHoldersFromreplacedembly).ToList();

            foreach (var holderType in holderTypes)
            {
                var specificationHolderTypes = holderType.GetInterfaces().Where(IsSpecificationHolderInterface).ToList();

                foreach (var specificationHolderType in specificationHolderTypes)
                {
                    var specifiedType = specificationHolderType.GetGenericArguments().Single();

                    holders.Add(new HolderInfo(holderType, specifiedType));
                }
            }

            return holders;

            IReadOnlyList<Type> GetAllSpecificationHoldersFromreplacedembly(replacedembly replacedembly)
            {
                return replacedembly
                    .GetTypes()
                    .Where(type => type.IsClreplaced &&
                                   type.GetConstructor(Type.EmptyTypes) != null &&
                                   type.GetInterfaces().Any(IsSpecificationHolderInterface))
                    .ToArray();
            }

            bool IsSpecificationHolderInterface(Type @interface)
            {
                return @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(ISpecificationHolder<>).GetGenericTypeDefinition();
            }
        }

See More Examples