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 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

TypeDoreplacedent CheckMember(TypeDoreplacedent doreplacedent, Type parent, MemberInfo member, Type memType, bool json, bool dc, bool checkBase = true)
        {
            if (doreplacedent.Fields.ContainsKey(member.Name))
                return null;
            var jp = member.GetAttribute<JsonPropertyAttribute>();
            var dm = member.GetAttribute<DataMemberAttribute>();
            if (json)
            {
                var ji = member.GetAttribute<JsonIgnoreAttribute>();
                if (ji != null)
                {
                    return null;
                }
                if (jp == null)
                    return null;
            }
            else if (dc)
            {
                var id = member.GetAttribute<IgnoreDataMemberAttribute>();
                if (id != null)
                    return null;
            }

            var field = new TypeDoreplacedent();
            var doc = XmlMember.Find(parent, member.Name);
            field.Copy(doc);
            bool isArray = false;
            bool isDictionary = false;
            try
            {
                Type type = memType;
                if (memType.IsArray)
                {
                    isArray = true;
                    type = type.replacedembly.GetType(type.FullName.Split('[')[0]);
                }
                else if (type.IsGenericType)
                {
                    if (memType.IsSupperInterface(typeof(ICollection<>)))
                    {
                        isArray = true;
                        type = type.GetGenericArguments()[0];
                    }
                    else if (memType.IsSupperInterface(typeof(IDictionary<,>)))
                    {
                        var fields = type.GetGenericArguments();
                        field.Fields.Add("Key", ReadEnreplacedy(fields[0], "Key"));
                        field.Fields.Add("Value", ReadEnreplacedy(fields[1], "Value"));
                        isDictionary = true;
                        checkBase = false;
                    }
                }
                if (type.IsEnum)
                {
                    if (checkBase)
                        field = ReadEnreplacedy(type, member.Name);
                    field.ObjectType = ObjectType.Base;
                    field.IsEnum = true;
                }
                else if (type.IsBaseType())
                {
                    field.ObjectType = ObjectType.Base;
                }
                else if(!isDictionary)
                {
                    if (checkBase)
                        field = ReadEnreplacedy(type, member.Name);
                    field.ObjectType = ObjectType.Object;
                }
                field.TypeName = ReflectionHelper.GetTypeName(type);
            }
            catch
            {
                field.TypeName = "object";
            }
            if (isArray)
            {
                field.TypeName += "[]";
                field.ObjectType = ObjectType.Array;
            }
            else if (isDictionary)
            {
                field.TypeName = "Dictionary";
                field.ObjectType = ObjectType.Dictionary;
            }

            field.Name = member.Name;
            field.JsonName = member.Name;
            field.ClreplacedName = ReflectionHelper.GetTypeName(memType);

            if (!string.IsNullOrWhiteSpace(dm?.Name))
                field.JsonName = dm.Name;
            if (!string.IsNullOrWhiteSpace(jp?.PropertyName))
                field.JsonName = jp.PropertyName;
            var rule = member.GetAttribute<DataRuleAttribute>();
            if (rule != null)
            {
                field.CanNull = rule.CanNull;
                field.Regex = rule.Regex;
                if (rule.Min != long.MinValue)
                    field.Min = rule.Min;
                if (rule.Max != long.MinValue)
                    field.Max = rule.Max;
                if (rule.MinDate != DateTime.MinValue)
                    field.MinDate = rule.MinDate;
                if (rule.MaxDate != DateTime.MaxValue)
                    field.MaxDate = rule.MaxDate;
            }
            doreplacedent.Fields.Add(member.Name, field);

            return field;
        }

19 View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
        {
            var enreplacedy = await _session.LoadAsync<TEnreplacedy>($"{_enreplacedybasePath}{id}", cancellationToken).ConfigureAwait(false);
            if (enreplacedy == null)
            {
                throw new InvalidOperationException($"Enreplacedy type {typeof(TEnreplacedy).Name} at id {id} is not found");
            }
            _session.Delete(enreplacedy);
            var iCollectionType = typeof(ICollection<>);
            var iEnreplacedyIdType = typeof(IEnreplacedyId);
            var subEnreplacediesProperties = _enreplacedyType.GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.ImplementsGenericInterface(iCollectionType) && p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(iEnreplacedyIdType));
            foreach(var subEnreplacedyProperty in subEnreplacediesProperties)
            {
                var collection = subEnreplacedyProperty.GetValue(enreplacedy) as ICollection;
                if (collection != null)
                {
                    foreach (IEnreplacedyId subItem in collection)
                    {
                        _session.Delete(subItem.Id);
                    }
                }
            }

            await OnDeleteEnreplacedyAsync(enreplacedy, cancellationToken).ConfigureAwait(false);

            await _session.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
            _logger.LogInformation("Enreplacedy {EnreplacedyId} deleted", enreplacedy.Id);
        }

19 View Source File : ImmutableCollectionDecorator.cs
License : MIT License
Project Creator : 404Lcc

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null) return false;
#if WINRT || COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if(!declaredTypeInfo.IsGenericType) return false;

#if WINRT || COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if WINRT || PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : adamant

public static string GetFriendlyName(this Type type)
        {
            if (type.IsGenericParameter || !type.IsGenericType)
                return type.Name;

            var name = type.Name;
            var index = name.IndexOf("`", StringComparison.Ordinal);
            name = name.Substring(0, index);
            var genericArguments = string.Join(',', type.GetGenericArguments().Select(GetFriendlyName));
            return $"{name}<{genericArguments}>";
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static T To<T>(this object value)
        {
            if (value == null) return default(T);
            Type tp = typeof(T);
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return (T)value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return (T)parameters[1];
            }
            return default(T);
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
    {
        if (type == null) return null;
        if (type == typeof(void)) return "void";
        if (type.IsGenericParameter) return type.Name;
        if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
        var sb = new StringBuilder();
        var nestedType = type;
        while (nestedType.IsNested)
        {
            sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
            nestedType = nestedType.DeclaringType;
        }
        if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
            sb.Insert(0, ".").Insert(0, nestedType.Namespace);

        if (type.IsGenericType == false)
            return sb.Append(type.Name).ToString();

        var genericParameters = type.GetGenericArguments();
        if (type.IsNested && type.DeclaringType.IsGenericType)
        {
            var dic = genericParameters.ToDictionary(a => a.Name);
            foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                if (dic.ContainsKey(nestedGenericParameter.Name))
                    dic.Remove(nestedGenericParameter.Name);
            genericParameters = dic.Values.ToArray();
        }
        if (genericParameters.Any() == false)
            return sb.Append(type.Name).ToString();

        sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
        var genericTypeIndex = 0;
        foreach (var genericType in genericParameters)
        {
            if (genericTypeIndex++ > 0) sb.Append(", ");
            sb.Append(DisplayCsharp(genericType, true));
        }
        return sb.Append(">").ToString();
    }

19 View Source File : AuthenticationSchemeOptionsSerializer.cs
License : MIT License
Project Creator : Aguafrommars

private TypeDefinition CreateTypeDefinition(Type type)
        {
            if (type.IsGenericType)
            {
                var genericType = type.GetGenericTypeDefinition();
                return new TypeDefinition
                {
                    Name = genericType.FullName,
                    ArgsTypeDefinition = type
                       .GetGenericArguments().Select(CreateTypeDefinition).ToArray()
                };
            }

            return new TypeDefinition
            {
                Name = type.FullName
            };
        }

19 View Source File : TccMaster.cs
License : MIT License
Project Creator : 2881099

TccMaster<TDBKey> Then(Type tccUnitType, object state)
        {
            if (tccUnitType == null) throw new ArgumentNullException(nameof(tccUnitType));
            var unitTypeBase = typeof(TccUnit<>);
            if (state == null && tccUnitType.BaseType.GetGenericTypeDefinition() == typeof(TccUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(tccUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(tccUnitType) == false) throw new ArgumentException($"{tccUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = tccUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{tccUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(tccUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{tccUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ITccUnit;
            (unit as ITccUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new TccUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = TccUnitStage.Try,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = tccUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : MetadataJsonConverter.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public override bool CanConvert(Type objectType)
        {
            if (objectType.IsGenericType)
            {
                objectType = objectType.GetGenericArguments()[0];
            }
            return objectType.GetInterface(typeof(IEnreplacedyId).FullName) != null;
        }

19 View Source File : DynamicProxyExtensions.cs
License : MIT License
Project Creator : 2881099

internal static Type ReturnTypeWithoutTask(this Type that)
        {
            if (that.IsTask() == false) return that;
            return that.GetGenericArguments().FirstOrDefault() ?? typeof(void);
        }

19 View Source File : Serializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private void InitializeDictionaries()
        {
            foreach (Type type in typeof(Serializer).replacedembly.GetTypes())
            {
                Type serializerType = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IObjectSerializer<>)).FirstOrDefault();
                if (serializerType is not null)
                {
                    object serializer = _factory.CreateInstance(type);
                    Type genericParameter = serializerType.GetGenericArguments().FirstOrDefault();
                    Serializers.Add(genericParameter, serializer);
                }
            }
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapDictionary(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Amf3Dictionary<,>));
            var tKey = valueType.GetGenericArguments().First();
            var tValue = valueType.GetGenericArguments().Last();

            _writeDictionaryTMethod.MakeGenericMethod(tKey, tValue).Invoke(this, new object[] { value, context });
        }

19 View Source File : DynamicProxyExtensions.cs
License : MIT License
Project Creator : 2881099

internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
        {
            if (type == null) return null;
            if (type == typeof(void)) return "void";
            if (type.IsGenericParameter) return type.Name;
            if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
            var sb = new StringBuilder();
            var nestedType = type;
            while (nestedType.IsNested)
            {
                sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
                nestedType = nestedType.DeclaringType;
            }
            if (isNameSpace && string.IsNullOrEmpty(nestedType.Namespace) == false)
                sb.Insert(0, ".").Insert(0, nestedType.Namespace);

            if (type.IsGenericType == false)
                return sb.Append(type.Name).ToString();

            var genericParameters = type.GetGenericArguments();
            if (type.IsNested && type.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any() == false)
                return sb.Append(type.Name).ToString();

            sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
            var genericTypeIndex = 0;
            foreach (var genericType in genericParameters)
            {
                if (genericTypeIndex++ > 0) sb.Append(", ");
                sb.Append(DisplayCsharp(genericType, true));
            }
            return sb.Append(">").ToString();
        }

19 View Source File : OrganizationServiceContextInfo.cs
License : MIT License
Project Creator : Adoxio

private IDictionary<string, EnreplacedySetInfo> LoadEnreplacedySets(Func<PropertyInfo, EnreplacedyInfo, string> keySelector)
		{
			var dataContextPublicProperties = ContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

			var enreplacedySetTypes =
				from property in dataContextPublicProperties
				let propertyType = property.PropertyType
				where propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(IQueryable<>)
				let enreplacedyType = propertyType.GetGenericArguments().First()
				select new EnreplacedySetInfo(property, new EnreplacedyInfo(enreplacedyType));

			var enreplacedySets = new Dictionary<string, EnreplacedySetInfo>();

			foreach (var type in enreplacedySetTypes)
			{
				var key = keySelector(type.Property, type.Enreplacedy);

				if (!string.IsNullOrEmpty(key))
				{
					enreplacedySets.Add(key, type);
				}
			}

			return enreplacedySets;
		}

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string DisplayCsharp(this Type type, bool isNameSpace = true)
        {
            if (type == null) return null;
            if (type == typeof(void)) return "void";
            if (type.IsGenericParameter) return type.Name;
            if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
            var sb = new StringBuilder();
            var nestedType = type;
            while (nestedType.IsNested)
            {
                sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
                nestedType = nestedType.DeclaringType;
            }
            if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
                sb.Insert(0, ".").Insert(0, nestedType.Namespace);

            if (type.IsGenericType == false)
                return sb.Append(type.Name).ToString();

            var genericParameters = type.GetGenericArguments();
            if (type.IsNested && type.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any() == false)
                return sb.Append(type.Name).ToString();

            sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
            var genericTypeIndex = 0;
            foreach (var genericType in genericParameters)
            {
                if (genericTypeIndex++ > 0) sb.Append(", ");
                sb.Append(DisplayCsharp(genericType, true));
            }
            return sb.Append(">").ToString();
        }

19 View Source File : StoredProcHelper.cs
License : Apache License 2.0
Project Creator : agoda-com

public static void SetTypeMap(IEnumerable<Type> spTypes)
        {
            var spInterfaces = new[] { typeof(IStoredProc<>), typeof(IStoredProc<,>) };
            var dbTypes = spTypes
                .SelectMany(x => x.GetInterfaces())
                .Where(x => x.IsGenericType)
                .Where(x =>
                {
                    var typeDef = x.GetGenericTypeDefinition();
                    return spInterfaces.Any(sp => typeDef == sp);
                })
                .SelectMany(x => x.GetGenericArguments());

            foreach (var modelType in dbTypes)
            {
                SqlMapper.SetTypeMap(modelType, CreateMap(modelType));
            }
        }

19 View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc

internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
        {
            dictionaryType = keyType = valueType = null;
            try
            {
#if WINRT || COREFX || PROFILE259
				var info = memberType.GetTypeInfo();
#else
                var info = memberType;
#endif
			MethodInfo b, a, ar, f;
            if(ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out b, out a, out ar, out f))
                {
                    return false;
                }
                if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                {
#if PROFILE259
					var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments;
#else
					var typeArgs = memberType.GetGenericArguments();
#endif
					if (IsValidMapKeyType(typeArgs[0]))
                    {
                        keyType = typeArgs[0];
                        valueType = typeArgs[1];
                        dictionaryType = memberType;
                    }
                    return false;
                }
#if PROFILE259
				foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces)
#else
				foreach (var iType in memberType.GetInterfaces())
#endif
				{
#if WINRT || COREFX || PROFILE259
					info = iType.GetTypeInfo();
#else
                    info = iType;
#endif
                    if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                    {
                        if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
#if PROFILE259
						var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments;
#else
						var typeArgs = iType.GetGenericArguments();
#endif
						if (IsValidMapKeyType(typeArgs[0]))
                        {
                            keyType = typeArgs[0];
                            valueType = typeArgs[1];
                            dictionaryType = memberType;
                        }
                    }
                }
                if (dictionaryType == null) return false;

                // (note we checked the key type already)
                // not a map if value is repeated
                Type itemType = null, defaultType = null;
                model.ResolveListTypes(valueType, ref itemType, ref defaultType);
                if (itemType != null) return false;

                return dictionaryType != null;
            }
            catch
            {
                // if it isn't a good fit; don't use "map"
                return false;
            }
        }

19 View Source File : AuthorizedToken.razor.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private void SetValue(TimeSpan? time)
        {
            _updatingValue = true;

            if (!time.HasValue)
            {
                Value = default;
                ValueChanged.InvokeAsync(Value);
                TokenValueChanged.InvokeAsync(Value);
                _token.ValueString = null;
            }
            else
            {
                var timeValue = time.Value;
                var type = typeof(T);
                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }
                Value = (T)Convert.ChangeType(timeValue.TotalSeconds, type);
                ValueChanged.InvokeAsync(Value);
                TokenValueChanged.InvokeAsync(Value);
                _token.ValueString = timeValue.ToString(DISPLAY_FORMAT);
            }

            StateHasChanged();
            _updatingValue = false;
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

internal static bool TypeIsCollection(Type t, out ConstructorInfo constructor, out Type itemType, out bool isImplGenerIList, out bool IsImplIList, out bool isImplGenerICollec, out bool isImplIReadOnlyList)
        {
            constructor = null;
            itemType = null;
            IsImplIList = false;
            isImplGenerIList = false;
            isImplGenerICollec = false;
            isImplIReadOnlyList = false;

            if (t.IsInterface)
            {
                if (t == typeof(IEnumerable) || t == typeof(ICollection) || t == typeof(IList))
                {
                    itemType = typeof(object);
                    if (t == typeof(IList))
                    {
                        IsImplIList = true;
                    }

                    return true;
                }

                if (t.IsGenericType)
                {
                    Type genericType = t.GetGenericTypeDefinition();
                    if (genericType == typeof(IEnumerable<>) || genericType == typeof(IList<>) || genericType == typeof(ICollection<>) || genericType == typeof(ISet<>) || genericType == typeof(IReadOnlyList<>) || genericType == typeof(IReadOnlyCollection<>))
                    {
                        if (genericType == typeof(IList<>))
                        {
                            isImplGenerIList = true;
                            isImplGenerICollec = true;
                        }
                        else if (genericType == typeof(ICollection<>) || genericType == typeof(ISet<>))
                        {
                            isImplGenerICollec = true;
                        }
                        else if (genericType == typeof(IReadOnlyList<>))
                        {
                            isImplIReadOnlyList = true;
                        }

                        itemType = t.GetGenericArguments()[0];
                        return true;
                    }
                }

                return false;
            }

            if (t.IsGenericType)
            {
                Type genericType = t.GetGenericTypeDefinition();
                if (genericType == typeof(List<>))
                {
                    itemType = t.GetGenericArguments()[0];
                    isImplGenerIList = true;
                    IsImplIList = true;
                    isImplGenerICollec = true;
                    isImplIReadOnlyList = true;
                    constructor = t.GetConstructor(new Type[] { typeof(int) });
                    return true;
                }
            }

            bool isImplGenerIEnumerable = false;
            bool isImplICollection = false;
            Type generIEnumerableItemType = null;
            Type generILisreplacedemType = null;
            Type generICollectionItemType = null;

            Type[] intserfaces = t.GetInterfaces();
            foreach (Type item in intserfaces)
            {
                if (item.IsGenericType)
                {
                    Type genericTypeDefinition = item.GetGenericTypeDefinition();

                    if (genericTypeDefinition == typeof(IEnumerable<>))
                    {
                        isImplGenerIEnumerable = true;
                        generIEnumerableItemType = item.GetGenericArguments()[0];
                    }
                    else if (genericTypeDefinition == typeof(ICollection<>))
                    {
                        isImplGenerICollec = true;
                        generICollectionItemType = item.GetGenericArguments()[0];
                    }
                    else if (genericTypeDefinition == typeof(IList<>))
                    {
                        isImplGenerIList = true;
                        generILisreplacedemType = item.GetGenericArguments()[0];
                    }
                }
                else if (item == typeof(ICollection))
                {
                    isImplICollection = true;
                }
                else if (item == typeof(IList))
                {
                    IsImplIList = true;
                }
            }

            if (isImplGenerIList)
            {
                if (TryGetConstructorInfo(t, generILisreplacedemType, true, out constructor))
                {
                    itemType = generILisreplacedemType;
                    return true;
                }
            }

            if (isImplGenerICollec)
            {
                if (TryGetConstructorInfo(t, generICollectionItemType, true, out constructor))
                {
                    itemType = generICollectionItemType;
                    return true;
                }
            }

            if (isImplGenerIEnumerable && isImplICollection)
            {
                if (TryGetConstructorInfo(t, generIEnumerableItemType, false, out constructor))
                {
                    itemType = generIEnumerableItemType;
                    return true;
                }
            }

            if (IsImplIList)
            {
                if (TryGetConstructorInfo(t, typeof(object), true, out constructor))
                {
                    itemType = typeof(object);
                    return true;
                }
            }

            if (isImplICollection)
            {
                if (TryGetConstructorInfo(t, typeof(object), false, out constructor))
                {
                    itemType = typeof(object);
                    return true;
                }
            }

            return false;
        }

19 View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task PopulateSubEnreplacedyAsync(string idName, object subEnreplacedy)
        {
            var type = subEnreplacedy.GetType();
            var idProperty = type.GetProperty(idName);
            var id = idProperty.GetValue(subEnreplacedy);
            var loaded = await _session.LoadAsync<object>(id as string).ConfigureAwait(false);
            if (loaded == null)
            {
                return;
            }

            // remove navigation
            var iCollectionType = typeof(ICollection<>);
            var iEnreplacedyIdType = typeof(IEnreplacedyId);
            var subEnreplacediesProperties = type.GetProperties().Where(p => p.PropertyType.IsGenericType &&
                p.PropertyType.ImplementsGenericInterface(iCollectionType) &&
                p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(iEnreplacedyIdType));
            foreach (var subEnreplacedyProperty in subEnreplacediesProperties)
            {
                subEnreplacedyProperty.SetValue(loaded, null);
            }

            CloneEnreplacedy(subEnreplacedy, type, loaded);
            idProperty.SetValue(subEnreplacedy, ((IEnreplacedyId)loaded).Id);
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object To(this object value,Type tp)
        {
            if (value == null) return null;

            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return parameters[1];
            }
            return null;
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

internal static bool TypeIsDictionary(Type t, out ConstructorInfo constructor, out bool typeIsGeneric, out Type genericTypeDefinition, out Type genericKeyType, out Type genericValueType)
        {
            constructor = null;
            typeIsGeneric = false;
            genericKeyType = null;
            genericValueType = null;
            genericTypeDefinition = null;

            Type genericType = null;
            bool hasIDictionaryGeneric = false;
            bool hasIDictionary = false;

            if (t.IsInterface)
            {
                if (t == typeof(IDictionary))
                {
                    return true;
                }

                if (t.IsGenericType)
                {
                    genericTypeDefinition = t.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>) || genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
                    {
                        Type[] args = t.GetGenericArguments();
                        typeIsGeneric = true;
                        genericType = t;
                        genericKeyType = args[0];
                        genericValueType = args[1];
                        return true;
                    }
                }
                return false;
            }

            if (t.IsGenericType)
            {
                genericTypeDefinition = t.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Dictionary<,>) ||
                    genericTypeDefinition == typeof(SortedList<,>))
                {
                    constructor = t.GetAppointTypeCtor(typeof(int));
                    typeIsGeneric = true;
                    Type[] args = t.GetGenericArguments();
                    genericKeyType = args[0];
                    genericValueType = args[1];
                    return true;
                }
            }

            IEnumerable<Type> intserfaces = t.GetInterfaces();
            foreach (Type item in intserfaces)
            {
                if (item.IsGenericType)
                {
                    genericTypeDefinition = item.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>) ||
                        genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
                    {
                        genericType = item;
                        Type[] args = item.GetGenericArguments();
                        genericKeyType = args[0];
                        genericValueType = args[1];
                        hasIDictionaryGeneric = true;
                        break;
                    }
                }
                else if (item == typeof(IDictionary))
                {
                    hasIDictionary = true;
                }
            }

            if (hasIDictionaryGeneric)
            {
                typeIsGeneric = true;

                //clreplaced <T>:IDictionary<int,int>
                //     ctor( ReadOnlyDic<,> )
                //     ctor( Dictionary<,>  )
                if (TryGetConstructorInfo(t, genericKeyType, genericValueType, true, out constructor))
                {
                    return true;
                }
            }
            else if (hasIDictionary)
            {
                constructor = t.GetDefaultNoArgCtorOrAppointTypeCtor(typeof(IDictionary));
                if (constructor != null)
                {
                    return true;
                }
            }

            return false;
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapVector(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Vector<>));
            var vectorT = valueType.GetGenericArguments().First();

            _writeVectorTMethod.MakeGenericMethod(vectorT).Invoke(this, new object[] { value, context });
        }

19 View Source File : DynamicProxyExtensions.cs
License : MIT License
Project Creator : 2881099

internal static string DisplayCsharp(this MethodInfo method, bool isOverride)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            if (method.IsPublic) sb.Append("public ");
            if (method.Isreplacedembly) sb.Append("internal ");
            if (method.IsFamily) sb.Append("protected ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsStatic) sb.Append("static ");
            if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
            return sb.ToString();
        }

19 View Source File : VBExpressionEditorSyntaxLanguage.cs
License : MIT License
Project Creator : Actipro

private static void AppendTypeName(StringBuilder typeName, Type type) {
			var typeFullName = type.FullName;

			if (type.IsGenericType) {
				var tickIndex = typeFullName.IndexOf('`');
				if (tickIndex != -1) {
					typeName.Append(typeFullName.Substring(0, tickIndex));
					typeName.Append("(Of ");
					var genericArgumentIndex = 0;
					foreach (var genericArgument in type.GetGenericArguments()) {
						if (genericArgumentIndex++ > 0)
							typeName.Append(", ");

						AppendTypeName(typeName, genericArgument);
					}
					typeName.Append(")");
					return;
				}
			}

			typeName.Append(typeFullName);
		}

19 View Source File : GenericTypeExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static string GetGenericTypeName(this Type type)
        {
            var typeName = string.Empty;

            if (type.IsGenericType)
            {
                var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
                typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
            }
            else
            {
                typeName = type.Name;
            }

            return typeName;
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToProxy(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            var isResult = false;

            if (isAsync)
            {
                sb.AppendLine($"            await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isAsync)
            {
                sb.AppendLine($"            await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.After(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : ObjectFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private bool TryGetImplementation(Type inputType, out Type outputType)
        {
            if (_interfaceImplementations.TryGetValue(inputType, out Type implementation))
            {
                outputType = implementation;
                return true;
            }

            if (inputType.IsGenericType && _interfaceImplementations.TryGetValue(inputType.GetGenericTypeDefinition(), out Type implementationType))
            {
                outputType = implementationType.MakeGenericType(inputType.GetGenericArguments());
                return true;
            }

            outputType = default;
            return false;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : MessageHandlerContainer.cs
License : MIT License
Project Creator : AdemCatamak

private static List<Type> GetPayloadTypes(Type messageHandlerType)
        {
            List<Type> payloadTypes = new List<Type>();
            foreach (Type interfaceType in messageHandlerType.GetInterfaces())
            {
                if (interfaceType.IsGenericType
                 && interfaceType.GetGenericTypeDefinition() == typeof(IMessageHandler<>))
                {
                    payloadTypes.Add(interfaceType.GetGenericArguments()[0]);
                }
            }

            return payloadTypes.Distinct().ToList();
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToMethod(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public static ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            var isResult = false;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : ReflectionExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string GetGenericParameter(this Type type)
        {
            var sb = new StringBuilder();
            var isFirst = true;
            foreach (var tParam in type.GetGenericArguments())
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    sb.Append(',');
                }
                sb.Append(ReflectionHelper.GetTypeName(tParam));
            }
            return sb.ToString();
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static TypeSyntax GenerateType(Type type)
        {
            if (!type.IsGenericType)
                return GenerateQualifiedNameSyntax(type);


            var list = new List<SyntaxNodeOrToken>();
            foreach (var genericType in type.GetGenericArguments())
            {
                list.Add(genericType.IsGenericType ? GenerateType(genericType) : GenerateQualifiedNameSyntax(genericType.FullName));
                list.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }
            var typeArgumentList = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList<TypeSyntax>(list.Take(list.Count - 1)));
            //if (type.Namespace == typeof(Task).Namespace)
            return SyntaxFactory.GenericName(type.Name.Substring(0, type.Name.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
            //return SyntaxFactory.GenericName(type.FullName?.Substring(0, type.FullName.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
        }

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
        {
            if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
                type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
                type == typeof(object) || type == typeof(void) ||
                type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
                type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
                return;
            if (typeDocs.TryGetValue(type, out var doc))
            {
                foreach (var field in doc.Fields)
                {
                    if (typeDoreplacedent.Fields.ContainsKey(field.Key))
                        typeDoreplacedent.Fields[field.Key] = field.Value;
                    else
                        typeDoreplacedent.Fields.Add(field.Key, field.Value);
                }
                return;
            }
            if (typeDocs2.TryGetValue(type, out var _))
            {
                ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);

                return;
            }

            typeDocs2.Add(type, typeDoreplacedent);
            if (type.IsArray)
            {
                ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
                return;
            }
            if (type.IsGenericType && !type.IsValueType &&
                type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
            {
                ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
                return;
            }

            XmlMember.Find(type);
            if (type.IsEnum)
            {
                foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    if (field.IsSpecialName)
                    {
                        continue;
                    }
                    var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
                    if (info != null)
                    {
                        info.TypeName = "int";
                        info.Example = ((int)field.GetValue(null)).ToString();
                        info.JsonName = null;
                    }
                }
                typeDocs.Add(type, new TypeDoreplacedent
                {
                    fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
                });
                typeDoreplacedent.Copy(XmlMember.Find(type));
                return;
            }

            var dc = type.GetAttribute<DataContractAttribute>();
            var jo = type.GetAttribute<JsonObjectAttribute>();

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
            }
            foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
            }

            typeDocs.Add(type, new TypeDoreplacedent
            {
                fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
            });
            typeDoreplacedent.Copy(XmlMember.Find(type));
        }

19 View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

19 View Source File : ContainerAttributeUtils.cs
License : Apache License 2.0
Project Creator : agoda-com

public static Type MakeClosedType(Type definition, Type parameter)
        {
            // non-generic
            if (!definition.IsGenericTypeDefinition && !definition.IsGenericType)
            {
                return definition;
            }

            // closed generic
            if (definition.ContainsGenericParameters)
            {
                return definition.MakeGenericType(parameter);
            }
            
            // open generic
            var definitionStack = new Stack<Type>();
            var type = definition;
            while (!type.IsGenericTypeDefinition)
            {
                definitionStack.Push(type.GetGenericTypeDefinition());
                type = type.GetGenericArguments()[0];
            }
            type = type.MakeGenericType(parameter);
            while (definitionStack.Count > 0)
            {
                type = definitionStack.Pop().MakeGenericType(type);
            }

            return type;
        }

19 View Source File : SagaMaster.cs
License : MIT License
Project Creator : 2881099

SagaMaster<TDBKey> Then(Type sagaUnitType, object state)
        {
            if (sagaUnitType == null) throw new ArgumentNullException(nameof(sagaUnitType));
            var unitTypeBase = typeof(SagaUnit<>);
            if (state == null && sagaUnitType.BaseType.GetGenericTypeDefinition() == typeof(SagaUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(sagaUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(sagaUnitType) == false) throw new ArgumentException($"{sagaUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = sagaUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{sagaUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(sagaUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{sagaUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ISagaUnit;
            (unit as ISagaUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new SagaUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = SagaUnitStage.Commit,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = sagaUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : ContractResolver.cs
License : MIT License
Project Creator : Aguafrommars

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            var propertyInfo = member as PropertyInfo;
            var propertyType = propertyInfo?.PropertyType;
            property.ShouldSerialize = instance => propertyType != null && 
                (!propertyType.IsInterface || 
                    (typeof(IEnumerable).IsreplacedignableFrom(propertyType) &&
                    propertyType.IsGenericType 
                    && propertyType.GetGenericArguments().Any(a => !a.IsInterface))) 
                && !propertyType.IsSubclreplacedOf(typeof(Delegate));

            return property;
        }

19 View Source File : ImmutableCollectionDecorator.cs
License : MIT License
Project Creator : 404Lcc

static Type ResolveIReadOnlyCollection(Type declaredType, Type t)
        {
#if WINRT || COREFX || PROFILE259
			foreach (Type intImplBasic in declaredType.GetTypeInfo().ImplementedInterfaces)
            {
                TypeInfo intImpl = intImplBasic.GetTypeInfo();
                if (intImpl.IsGenericType && intImpl.Name.StartsWith("IReadOnlyCollection`"))
                {
                    if(t != null)
                    {
                        Type[] typeArgs = intImpl.GenericTypeArguments;
                        if (typeArgs.Length != 1 && typeArgs[0] != t) continue;
                    }
                    return intImplBasic;
                }
            }
#else
            foreach (Type intImpl in declaredType.GetInterfaces())
            {
                if (intImpl.IsGenericType && intImpl.Name.StartsWith("IReadOnlyCollection`"))
                {
                    if(t != null)
                    {
                        Type[] typeArgs = intImpl.GetGenericArguments();
                        if (typeArgs.Length != 1 && typeArgs[0] != t) continue;
                    }
                    return intImpl;
                }
            }
#endif
            return null;
        }

19 View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task<object> GetSubItemsAsync(TEnreplacedy enreplacedy, Type propertyType)
        {
            var storeType = typeof(IAdminStore<>).MakeGenericType(propertyType.GetGenericArguments()[0]);
            var subStore = _provider.GetRequiredService(storeType);
            var getPageResponseMethod = storeType.GetMethod(nameof(IAdminStore<object>.GetAsync), new[] { typeof(PageRequest), typeof(CancellationToken) });
            var task = getPageResponseMethod.Invoke(subStore, new[]
            {
                    new PageRequest
                    {
                        Filter = $"{GetSubEnreplacedyParentIdName(_enreplacedyType)} eq '{enreplacedy.Id}'",
                        Take = null
                    },
                    null
                });
            await (task as Task).ConfigureAwait(false);
            var response = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
            var items = response.GetType().GetProperty(nameof(PageResponse<object>.Items)).GetValue(response);
            return items;
        }

19 View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade

public static Type GetRequestType(this Type t) {
            Type[] interfaces = t.GetInterfaces();
            foreach (Type i in interfaces)
                if (i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IDataRequestable<>))
                    return i.GetGenericArguments()[0];
            throw new Exception($"Invalid requested type: {t.FullName}");
        }

19 View Source File : ImportService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task ImportSubEnreplacediesAsync(T enreplacedy, Dictionary<string, IEnumerable> subEnreplacedies, IAdminStore<T> store, ImportFileResult result)
            {                
                if (!subEnreplacedies.Any())
                {
                    return;
                }

                var expand = string.Join(",", subEnreplacedies.Keys);
                enreplacedy = await store.GetAsync(enreplacedy.Id, new GetRequest { Expand = expand }).ConfigureAwait(false);

                foreach (var key in subEnreplacedies.Keys)
                {
                    if (subEnreplacedies[key] == null)
                    {
                        continue;
                    }

                    var property = typeof(T).GetProperty(key);
                    var subEnreplacedyList = property.GetValue(enreplacedy) as IEnumerable;
                    var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
                    var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
                    var importer = Activator.CreateInstance(importerType, _provider) as Importer;
                    await importer.RemoveEnreplacediesAsync(subEnreplacedyList, result).ConfigureAwait(false);
                }

                foreach (var enreplacedyList in subEnreplacedies)
                {
                    var enumerator = enreplacedyList.Value.GetEnumerator();
                    if (!enumerator.MoveNext())
                    {
                        continue;
                    }

                    var enreplacedyType = enumerator.Current.GetType();
                    var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
                    var importer = Activator.CreateInstance(importerType, _provider) as Importer;

                    await importer.AddOrUpdateSubEnreplacediesAsync(enreplacedyList.Value, result).ConfigureAwait(false);
                }
            }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static Type GetNonNummableType(this Type type)
        {
            if (IsNullableType(type))
            {
                return type.GetGenericArguments()[0];
            }
            return type;
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

static string DisplayCsharp(this MethodInfo method, bool isOverride)
    {
        if (method == null) return null;
        var sb = new StringBuilder();
        if (method.IsPublic) sb.Append("public ");
        if (method.Isreplacedembly) sb.Append("internal ");
        if (method.IsFamily) sb.Append("protected ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsStatic) sb.Append("static ");
        if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
        if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
        sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

        var genericParameters = method.GetGenericArguments();
        if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
        {
            var dic = genericParameters.ToDictionary(a => a.Name);
            foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                if (dic.ContainsKey(nestedGenericParameter.Name))
                    dic.Remove(nestedGenericParameter.Name);
            genericParameters = dic.Values.ToArray();
        }
        if (genericParameters.Any())
            sb.Append("<")
                .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                .Append(">");

        sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
        return sb.ToString();
    }

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static void SerializeDictionaryHeader(Protocol16Stream output, Type dictionaryType, out bool writeKeyCode, out bool writeValueCode)
        {
            Type[] genericArguments = dictionaryType.GetGenericArguments();
            writeKeyCode = (genericArguments[0] == typeof(object));
            writeValueCode = (genericArguments[1] == typeof(object));
            if (writeKeyCode)
            {
                output.WriteTypeCodeIfTrue(Protocol16Type.Unknown, true);
            }
            else
            {
                Protocol16Type typeOfKey = TypeCodeToProtocol16Type(genericArguments[0]);
                if (typeOfKey == Protocol16Type.Unknown || typeOfKey == Protocol16Type.Dictionary)
                {
                    throw new Exception("Unexpected - cannot serialize Dictionary with key type: " + genericArguments[0]);
                }
                output.WriteTypeCodeIfTrue(typeOfKey, true);
            }
            if (writeValueCode)
            {
                output.WriteTypeCodeIfTrue(Protocol16Type.Unknown, true);
            }
            else
            {
                Protocol16Type typeOfValue = TypeCodeToProtocol16Type(genericArguments[1]);
                if (typeOfValue == Protocol16Type.Unknown)
                {
                    throw new Exception("Unexpected - cannot serialize Dictionary with value type: " + genericArguments[0]);
                }
                output.WriteTypeCodeIfTrue(typeOfValue, true);
                if (typeOfValue == Protocol16Type.Dictionary)
                {
                    throw new Exception("TODO: Nested Dictionaries");
                }
            }
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static void FindNamespace(Type type, List<string> namespaces)
        {
            if (type.Namespace == "System.Threading.Tasks" && !type.IsGenericType || type.Namespace == "System" || type.Namespace == "System.Collections.Generic")
                return;

            namespaces.Add(type.Namespace);
            if (!type.IsGenericType) return;
            foreach (var item in type.GetGenericArguments())
            {
                FindNamespace(item, namespaces);
            }
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToInterface(this MethodInfo method, bool isAlign = true)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            //if (method.IsPublic) sb.Append("public ");
            //if (method.Isreplacedembly) sb.Append("internal ");
            //if (method.IsFamily) sb.Append("protected ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsStatic) sb.Append("static ");
            //if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            //if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            if (isAlign)
                sb.Append("        ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");

            if (isAlign)
                sb.Append(";\r\n\r\n");

            return sb.ToString();
        }

19 View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider

private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
                (ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
                    .Select(item => (Expression.Parameter(typeof(object)), item))
                    .ToArray();

                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo,
                            argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
                        argObjectParameters.Select(item => item.expression))
                    .Compile();

                return method;
            }

See More Examples