System.Type.GetGenericArguments()

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

2739 Examples 7

19 Source : MetadataJsonConverter.cs
with Apache License 2.0
from Aguafrommars

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            var t = JToken.FromObject(value, _internaleSerializer);

            if (t.Type != JTokenType.Object)
            {
                t.WriteTo(writer);
            }
            else
            {
                var o = (JObject)t;

                var type = value.GetType();
                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }

                o.AddFirst(new JProperty("_metadata", JObject.FromObject(new { typeName = type.replacedemblyQualifiedName }, _internaleSerializer)));

                o.WriteTo(writer);
            }
        }

19 Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars

public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
        {
            using var session = await _collection.Database.Client.StartSessionAsync(cancellationToken: cancellationToken);

            var isTransactionSupported = session.Client.Cluster.Description.Type != ClusterType.Standalone;
            if (isTransactionSupported)
            {
                session.StartTransaction();
            }

            var enreplacedy = await _collection.AsQueryable()
                .FirstOrDefaultAsync(e => e.Id == id, cancellationToken)
                .ConfigureAwait(false);

            if (enreplacedy == null)
            {
                throw new InvalidOperationException($"Enreplacedy type {typeof(TEnreplacedy).Name} at id {id} is not found");
            }

            await _collection.DeleteOneAsync(session, Builders<TEnreplacedy>.Filter.Eq(e => e.Id, id), cancellationToken: cancellationToken).ConfigureAwait(false);
            
            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));

            var dataBase = _collection.Database;
            foreach (var subEnreplacedyProperty in subEnreplacediesProperties)
            {
                var subCollection = dataBase.GetCollection<BsonDoreplacedent>(subEnreplacedyProperty.PropertyType.GetGenericArguments()[0].Name);
                await subCollection.DeleteManyAsync(session, new BsonDoreplacedent(GetSubEnreplacedyParentIdName(_enreplacedyType), id), cancellationToken: cancellationToken).ConfigureAwait(false);
            }

            if (isTransactionSupported)
            {
                await session.CommitTransactionAsync(cancellationToken).ConfigureAwait(false);
            }

            _logger.LogInformation("Enreplacedy {EnreplacedyId} deleted", enreplacedy.Id, enreplacedy);
        }

19 Source : AdminStoreTestBase.cs
with Apache License 2.0
from Aguafrommars

private async Task<TEnreplacedy> CreateEnreplacedyGraphAsync(IEnumerable<PropertyInfo> navigationProperties, ServiceProvider provider, IAdminStore<TEnreplacedy> sut)
        {
            var create = new TEnreplacedy
            {
                Id = Guid.NewGuid().ToString()
            };
            var parentPropetyName = GetParentIdName(create.GetType());
            if (parentPropetyName != null)
            {
                var parentPropetyType = GetParentType(parentPropetyName);
                await AddParentEnreplacedy(provider, create, parentPropetyName, parentPropetyType).ConfigureAwait(false);
            }
            var enreplacedy = await sut.CreateAsync(create).ConfigureAwait(false);
            foreach (var property in navigationProperties)
            {
                var subEnreplacedyType = property.PropertyType;
                if (subEnreplacedyType.ImplementsGenericInterface(typeof(ICollection<>)))
                {
                    subEnreplacedyType = subEnreplacedyType.GetGenericArguments()[0];
                    var parentPropety = subEnreplacedyType.GetProperty(GetSubEnreplacedyParentIdName(enreplacedy.GetType()));
                    var subEnreplacedy = Activator.CreateInstance(subEnreplacedyType);
                    parentPropety.SetValue(subEnreplacedy, enreplacedy.Id);

                    var storeType = typeof(IAdminStore<>).MakeGenericType(subEnreplacedyType);
                    var subStore = provider.GetRequiredService(storeType) as IAdminStore;
                    await subStore.CreateAsync(subEnreplacedy).ConfigureAwait(false);
                    continue;
                }

                await AddParentEnreplacedy(provider, create, $"{property.Name}Id", property.PropertyType).ConfigureAwait(false);
            }
            await sut.UpdateAsync(enreplacedy).ConfigureAwait(false);

            return enreplacedy;
        }

19 Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars

private static void AddStoresForContext(IServiceCollection services, Type dbContextType)
        {
            foreach (var property in dbContextType.GetProperties().Where(p => p.PropertyType.ImplementsGenericInterface(typeof(IQueryable<>)) &&
                p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(typeof(IEnreplacedyId))))
            {
                var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
                var adminStoreType = typeof(AdminStore<,>)
                        .MakeGenericType(enreplacedyType.GetTypeInfo(), dbContextType.GetTypeInfo()).GetTypeInfo();
                services.AddTransient(adminStoreType);

                var cacheAdminStoreType = typeof(CacheAdminStore<,>)
                        .MakeGenericType(adminStoreType.GetTypeInfo(), enreplacedyType.GetTypeInfo()).GetTypeInfo();
                services.AddTransient(cacheAdminStoreType);

                var iAdminStoreType = typeof(IAdminStore<>)
                        .MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
                services.AddTransient(iAdminStoreType, cacheAdminStoreType);
            }
        }

19 Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars

private async Task PopulateSubEnreplacediesAsync(string idName, string path, TEnreplacedy enreplacedy)
        {
            var property = _enreplacedyType.GetProperty(path);
            var value = property.GetValue(enreplacedy);
            if (value == null)
            {
                if (property.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)))
                {
                    value = Activator.CreateInstance(typeof(Collection<>).MakeGenericType(property.PropertyType.GetGenericArguments()));
                }
                else
                {
                    value = Activator.CreateInstance(property.PropertyType);
                }
                
                property.SetValue(enreplacedy, value);
            }

            if (value is ICollection collection)
            {
                foreach (var v in collection)
                {
                    await PopulateSubEnreplacedyAsync("Id", v).ConfigureAwait(false);
                    var idProperty = v.GetType().GetProperty(idName);
                    idProperty.SetValue(v, enreplacedy.Id);
                }
                return;
            }

            var parentIdProperty = _enreplacedyType.GetProperty($"{path}Id");
            ((IEnreplacedyId)value).Id = parentIdProperty.GetValue(enreplacedy) as string;
            await PopulateSubEnreplacedyAsync("Id", value).ConfigureAwait(false);
            parentIdProperty.SetValue(enreplacedy, ((IEnreplacedyId)value).Id);
        }

19 Source : ValidationAspect.cs
with MIT License
from ahmet-cetinkaya

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

19 Source : DbContextOptionsSpecimenBuilder.cs
with MIT License
from aivascu

public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!this.OptionsSpecification.IsSatisfiedBy(request))
            {
                return new NoSpecimen();
            }

            if (!(request is Type type))
            {
                return new NoSpecimen();
            }

            var contextType = type.GetGenericArguments().Single();

            var optionsBuilderObj = context.Resolve(typeof(IOptionsBuilder));

            if (optionsBuilderObj is NoSpecimen
                || optionsBuilderObj is OmitSpecimen
                || optionsBuilderObj is null)
            {
                return optionsBuilderObj;
            }

            if (!(optionsBuilderObj is IOptionsBuilder optionsBuilder))
            {
                return new NoSpecimen();
            }

            return optionsBuilder.Build(contextType);
        }

19 Source : InstranceMaker.cs
with MIT License
from AiursoftWeb

public static object Make(this Type type)
        {
            if (type == typeof(string))
            {
                return "an example string.";
            }
            else if (type == typeof(int) || type == typeof(int?))
            {
                return 0;
            }
            else if (type == typeof(DateTime) || type == typeof(DateTime?))
            {
                return DateTime.UtcNow;
            }
            else if (type == typeof(Guid) || type == typeof(Guid?))
            {
                return Guid.NewGuid();
            }
            else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
            {
                return DateTimeOffset.UtcNow;
            }
            else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?))
            {
                return TimeSpan.FromMinutes(37);
            }
            else if (type == typeof(bool) || type == typeof(bool?))
            {
                return true;
            }
            // List
            else if (type.IsGenericType && type.GetGenericTypeDefinition().GetInterfaces().Any(t => t.IsreplacedignableFrom(typeof(IEnumerable))))
            {
                var itemType = type.GetGenericArguments()[0];
                return GetArrayWithInstanceInherts(itemType);
            }
            // Array
            else if (type.GetInterface(typeof(IEnumerable<>).FullName ?? string.Empty) != null)
            {
                var itemType = type.GetElementType();
                var list = GetArrayWithInstanceInherts(itemType);
                var array = Array.CreateInstance(itemType ?? typeof(string[]), list.Count);
                list.CopyTo(array, 0);
                return array;
            }
            else
            {
                var instance = GenerateWithConstructor(type);
                if (instance != null)
                {
                    foreach (var property in instance.GetType().GetProperties())
                    {
                        if (property.CustomAttributes.Any(t => t.AttributeType == typeof(JsonIgnoreAttribute)))
                        {
                            property.SetValue(instance, null);
                        }
                        else if (property.CustomAttributes.Any(t => t.AttributeType == typeof(InstanceMakerIgnore)))
                        {
                            property.SetValue(instance, null);
                        }
                        else if (property.SetMethod != null)
                        {
                            property.SetValue(instance, Make(property.PropertyType));
                        }
                    }
                }
                return instance;
            }
        }

19 Source : KeyValuePairConverter.cs
with MIT License
from akaskela

private static ReflectionObject InitializeReflectionObject(Type t)
        {
            IList<Type> genericArguments = t.GetGenericArguments();
            Type keyType = genericArguments[0];
            Type valueType = genericArguments[1];

            return ReflectionObject.Create(t, t.GetConstructor(new[] { keyType, valueType }), KeyName, ValueName);
        }

19 Source : DefaultContractResolver.cs
with MIT License
from akaskela

private MemberInfo GetExtensionDataMemberForType(Type type)
        {
            IEnumerable<MemberInfo> members = GetClreplacedHierarchyForType(type).SelectMany(baseType =>
            {
                IList<MemberInfo> m = new List<MemberInfo>();
                m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
                m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));

                return m;
            });

            MemberInfo extensionDataMember = members.LastOrDefault(m =>
            {
                MemberTypes memberType = m.MemberType();
                if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)
                {
                    return false;
                }

                // last instance of attribute wins on type if there are multiple
                if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
                {
                    return false;
                }

                if (!ReflectionUtils.CanReadMemberValue(m, true))
                {
                    throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
                }

                Type t = ReflectionUtils.GetMemberUnderlyingType(m);

                Type dictionaryType;
                if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
                {
                    Type keyType = dictionaryType.GetGenericArguments()[0];
                    Type valueType = dictionaryType.GetGenericArguments()[1];

                    if (keyType.IsreplacedignableFrom(typeof(string)) && valueType.IsreplacedignableFrom(typeof(JToken)))
                    {
                        return true;
                    }
                }

                throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
            });

            return extensionDataMember;
        }

19 Source : DefaultContractResolver.cs
with MIT License
from akaskela

private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member)
        {
            JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute<JsonExtensionDataAttribute>(member);
            if (extensionDataAttribute == null)
            {
                return;
            }

            Type t = ReflectionUtils.GetMemberUnderlyingType(member);

            Type dictionaryType;
            ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType);

            Type keyType = dictionaryType.GetGenericArguments()[0];
            Type valueType = dictionaryType.GetGenericArguments()[1];

            Type createdType;

            // change type to a clreplaced if it is the base interface so it can be instantiated if needed
            if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>)))
            {
                createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
            }
            else
            {
                createdType = t;
            }

            Func<object, object> getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(member);

            if (extensionDataAttribute.ReadData)
            {
                Action<object, object> setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false))
                 ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(member)
                 : null;
                Func<object> createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
                MethodInfo addMethod = t.GetMethod("Add", new[] { keyType, valueType });
                MethodCall<object, object> setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(addMethod);

                ExtensionDataSetter extensionDataSetter = (o, key, value) =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        if (setExtensionDataDictionary == null)
                        {
                            throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name));
                        }

                        dictionary = createExtensionDataDictionary();
                        setExtensionDataDictionary(o, dictionary);
                    }

                    setExtensionDataDictionaryValue(dictionary, key, value);
                };

                contract.ExtensionDataSetter = extensionDataSetter;
            }

            if (extensionDataAttribute.WriteData)
            {
                Type enumerableWrapper = typeof(EnumerableDictionaryWrapper<,>).MakeGenericType(keyType, valueType);
                ConstructorInfo constructors = enumerableWrapper.GetConstructors().First();
                ObjectConstructor<object> createEnumerableWrapper = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructors);

                ExtensionDataGetter extensionDataGetter = o =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        return null;
                    }

                    return (IEnumerable<KeyValuePair<object, object>>)createEnumerableWrapper(dictionary);
                };

                contract.ExtensionDataGetter = extensionDataGetter;
            }

            contract.ExtensionDataValueType = valueType;
        }

19 Source : ReflectionUtils.cs
with MIT License
from akaskela

public static Type GetCollectionItemType(Type type)
        {
            ValidationUtils.ArgumentNotNull(type, nameof(type));
            Type genericListType;

            if (type.IsArray)
            {
                return type.GetElementType();
            }
            if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
            {
                if (genericListType.IsGenericTypeDefinition())
                {
                    throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
                }

                return genericListType.GetGenericArguments()[0];
            }
            if (typeof(IEnumerable).IsreplacedignableFrom(type))
            {
                return null;
            }

            throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
        }

19 Source : ReflectionUtils.cs
with MIT License
from akaskela

public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
        {
            ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));

            Type genericDictionaryType;
            if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
            {
                if (genericDictionaryType.IsGenericTypeDefinition())
                {
                    throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
                }

                Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();

                keyType = dictionaryGenericArguments[0];
                valueType = dictionaryGenericArguments[1];
                return;
            }
            if (typeof(IDictionary).IsreplacedignableFrom(dictionaryType))
            {
                keyType = null;
                valueType = null;
                return;
            }

            throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
        }

19 Source : NodeEditorReflection.cs
with MIT License
from aksyr

public static void OpenPreferences() {
            try {
#if UNITY_2018_3_OR_NEWER
                SettingsService.OpenUserPreferences("Preferences/Node Editor");
#else
                //Open preferences window
                replacedembly replacedembly = replacedembly.Getreplacedembly(typeof(UnityEditor.EditorWindow));
                Type type = replacedembly.GetType("UnityEditor.PreferencesWindow");
                type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);

                //Get the window
                EditorWindow window = EditorWindow.GetWindow(type);

                //Make sure custom sections are added (because waiting for it to happen automatically is too slow)
                FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance);
                if ((bool) refreshField.GetValue(window)) {
                    type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null);
                    refreshField.SetValue(window, false);
                }

                //Get sections
                FieldInfo sectionsField = type.GetField("m_Sections", BindingFlags.Instance | BindingFlags.NonPublic);
                IList sections = sectionsField.GetValue(window) as IList;

                //Iterate through sections and check contents
                Type sectionType = sectionsField.FieldType.GetGenericArguments() [0];
                FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public);
                for (int i = 0; i < sections.Count; i++) {
                    GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent;
                    if (sectionContent.text == "Node Editor") {
                        //Found contents - Set index
                        FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic);
                        sectionIndexField.SetValue(window, i);
                        return;
                    }
                }
#endif
            } catch (Exception e) {
                Debug.LogError(e);
                Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number.");
            }
        }

19 Source : NodeEditorUtilities.cs
with MIT License
from aksyr

public static string PrettyName(this Type type) {
            if (type == null) return "null";
            if (type == typeof(System.Object)) return "object";
            if (type == typeof(float)) return "float";
            else if (type == typeof(int)) return "int";
            else if (type == typeof(long)) return "long";
            else if (type == typeof(double)) return "double";
            else if (type == typeof(string)) return "string";
            else if (type == typeof(bool)) return "bool";
            else if (type.IsGenericType) {
                string s = "";
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(List<>)) s = "List";
                else s = type.GetGenericTypeDefinition().ToString();

                Type[] types = type.GetGenericArguments();
                string[] stypes = new string[types.Length];
                for (int i = 0; i < types.Length; i++) {
                    stypes[i] = types[i].PrettyName();
                }
                return s + "<" + string.Join(", ", stypes) + ">";
            } else if (type.IsArray) {
                string rank = "";
                for (int i = 1; i < type.GetArrayRank(); i++) {
                    rank += ",";
                }
                Type elementType = type.GetElementType();
                if (!elementType.IsArray) return elementType.PrettyName() + "[" + rank + "]";
                else {
                    string s = elementType.PrettyName();
                    int i = s.IndexOf('[');
                    return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i);
                }
            } else return type.ToString();
        }

19 Source : PortView.cs
with MIT License
from alelievr

public virtual void Initialize(BaseNodeView nodeView, string name)
		{
			this.owner = nodeView;
			AddToClreplacedList(fieldName);

			// Correct port type if port accept multiple values (and so is a container)
			if (direction == Direction.Input && portData.acceptMultipleEdges && portType == fieldType) // If the user haven't set a custom field type
			{
				if (fieldType.GetGenericArguments().Length > 0)
					portType = fieldType.GetGenericArguments()[0];
			}

			if (name != null)
				portName = name;
			visualClreplaced = "Port_" + portType.Name;
			tooltip = portData.tooltip;
		}

19 Source : ColorTheme.cs
with MIT License
from alelievr

public static ColorSchemeName GetAnchorColorSchemeName(Type fieldType)
		{
			if (fieldType.IsGenericType)
				fieldType = fieldType.GetGenericArguments()[0];
			
			foreach (var kp in anchorColorSchemeNames)
				foreach (var type in kp.Value)
					if (type == fieldType || fieldType.IsSubclreplacedOf(type))
						return kp.Key;
			
			return ColorSchemeName.Default;
		}

19 Source : AnchorUtils.cs
with MIT License
from alelievr

static bool				Arereplacedignable(Type from, Type to)
		{
			if (to == typeof(object))
				return true;
			
			if (from == null || to == null)
				return false;

			//if to or from are PWArray, we replace the to/from type by their generic type
			if (to.IsGenericType && to.GetGenericTypeDefinition() == typeof(PWArray<>))
				to = to.GetGenericArguments()[0];
			if (from.IsGenericType && from.GetGenericTypeDefinition() == typeof(PWArray<>))
				from = from.GetGenericArguments()[0];

			if (from == to)
				return true;
			
			//Allow parrent -> child replacedignation but also child -> parrent
			if (from.IsreplacedignableFrom(to) || to.IsreplacedignableFrom(from))
				return true;

			return false;
		}

19 Source : Reflection.cs
with MIT License
from AlenToma

internal static FieldInfo GetGetterBackingField(PropertyInfo autoProperty)
        {
            var getMethod = autoProperty.GetGetMethod();
            // Restrict operation to auto properties to avoid risking errors if a getter does not contain exactly one field read instruction (such as with calculated properties).
            if (!getMethod.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false)) return null;

            var byteCode = getMethod.GetMethodBody()?.GetILAsByteArray() ?? new byte[0];
            //var byteCode = getMethod.GetMethodBody().GetILAsByteArray();
            int pos = 0;
            // Find the first LdFld instruction and parse its operand to a FieldInfo object.
            while (pos < byteCode.Length)
            {
                // Read and parse the OpCode (it can be 1 or 2 bytes in size).
                byte code = byteCode[pos++];
                if (!(TryGetOpCode(code, out var opCode) || pos < byteCode.Length && TryGetOpCode((short)(code * 0x100 + byteCode[pos++]), out opCode)))
                    throw new NotSupportedException("Unknown IL code detected.");
                // If it is a LdFld, read its operand, parse it to a FieldInfo and return it.
                if (opCode == OpCodes.Ldfld && opCode.OperandType == OperandType.InlineField && pos + sizeof(int) <= byteCode.Length)
                {
                    return getMethod.Module.ResolveMember(BitConverter.ToInt32(byteCode, pos), getMethod.DeclaringType?.GetGenericArguments(), null) as FieldInfo;
                }
                // Otherwise, set the current position to the start of the next instruction, if any (we need to know how much bytes are used by operands).
                pos += opCode.OperandType == OperandType.InlineNone
                            ? 0
                            : opCode.OperandType == OperandType.ShortInlineBrTarget ||
                              opCode.OperandType == OperandType.ShortInlineI ||
                              opCode.OperandType == OperandType.ShortInlineVar
                                ? 1
                                : opCode.OperandType == OperandType.InlineVar
                                    ? 2
                                    : opCode.OperandType == OperandType.InlineI8 ||
                                      opCode.OperandType == OperandType.InlineR
                                        ? 8
                                        : opCode.OperandType == OperandType.InlineSwitch
                                            ? 4 * (BitConverter.ToInt32(byteCode, pos) + 1)
                                            : 4;
            }
            return null;
        }

19 Source : Extension.cs
with MIT License
from AlenToma

public static bool IsNumeric(this Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = type.GetGenericArguments().FirstOrDefault() ?? type;
            return type.IsPrimitive && type != typeof(char) && type != typeof(bool);
        }

19 Source : TypeHelper.cs
with MIT License
from AlenToma

public static Type GetElementType(Type seqType)
        {
            Type ienum = FindIEnumerable(seqType);
            if (ienum == null) return seqType;
            return ienum.GetGenericArguments()[0];
        }

19 Source : TypeHelper.cs
with MIT License
from AlenToma

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

19 Source : Reflection.cs
with MIT License
from AlenToma

public Type[] GetGenericArguments(Type t)
        {
            Type[] tt = null;
            if (_genericTypes.TryGetValue(t, out tt))
                return tt;
            else
            {
                tt = t.GetGenericArguments();
                _genericTypes.Add(t, tt);
                return tt;
            }
        }

19 Source : LightDataTableRow.cs
with MIT License
from AlenToma

public object ValueAndConvert(Type type, string key, bool loadDefault = false)
        {
            var v = this[key, loadDefault];
            if (v != DBNull.Value && v != null && v.GetType() != Columns[key].DataType && !(type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>)) && v != "")
                return Convert.ChangeType(this[key], type);
            if (v == null || v == DBNull.Value || string.IsNullOrEmpty(v.ToString()))
            {
                TypeValidation(ref v, type, true);
                if (v == null && type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>))
                    return ValueByType(type);
            }
            else
                TypeValidation(ref v, type, false);

            if (v?.GetType() != type && (!type.GetTypeInfo().IsGenericType || type.GetTypeInfo().GetGenericTypeDefinition() != typeof(Nullable<>)))
                return Convert.ChangeType(v, type);

            return v?.GetType() != type ? Convert.ChangeType(v, type.GetGenericArguments()[0]) : v;
        }

19 Source : TypeHelper.cs
with MIT License
from AlenToma

public static Type FindIEnumerable(Type seqType)
        {
            if (seqType == null || seqType == typeof(string))
                return null;
            if (seqType.IsArray)
                return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
            if (seqType.IsGenericType)
            {
                foreach (Type arg in seqType.GetGenericArguments())
                {
                    Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
                    if (ienum.IsreplacedignableFrom(seqType))
                    {
                        return ienum;
                    }
                }
            }
            Type[] ifaces = seqType.GetInterfaces();
            if (ifaces != null && ifaces.Length > 0)
            {
                foreach (Type iface in ifaces)
                {
                    Type ienum = FindIEnumerable(iface);
                    if (ienum != null) return ienum;
                }
            }
            if (seqType.BaseType != null && seqType.BaseType != typeof(object))
            {
                return FindIEnumerable(seqType.BaseType);
            }
            return null;
        }

19 Source : OpenApiSchemaExtensions.cs
with MIT License
from aliencube

[Obsolete("This method is now obsolete", error: true)]
        public static Dictionary<string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
        {
            type.ThrowIfNullOrDefault();

            var schema = (OpenApiSchema)null;
            var schemeName = type.GetOpenApiTypeName(namingStrategy);

            if (depth == 8)
            {
                schema = new OpenApiSchema()
                {
                    Type = type.ToDataType(),
                    Format = type.ToDataFormat()
                };

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            depth++;

            if (type.IsJObjectType())
            {
                schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiNullable(out var unwrappedValueType))
            {
                schema = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
                schema.Nullable = true;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            schema = new OpenApiSchema()
            {
                Type = type.ToDataType(),
                Format = type.ToDataFormat()
            };

            if (!attribute.IsNullOrDefault())
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                schema.Extensions.Add("x-ms-visibility", visibility);
            }

            if (type.IsUnflaggedEnumType())
            {
                var converterAttribute = type.GetCustomAttribute<JsonConverterAttribute>();
                if (!converterAttribute.IsNullOrDefault()
                    && typeof(StringEnumConverter).IsreplacedignableFrom(converterAttribute.ConverterType))
                {
                    var enums = type.ToOpenApiStringCollection(namingStrategy);

                    schema.Type = "string";
                    schema.Format = null;
                    schema.Enum = enums;
                    schema.Default = enums.First();
                }
                else
                {
                    var enums = type.ToOpenApiIntegerCollection();

                    schema.Enum = enums;
                    schema.Default = enums.First();
                }
            }

            if (type.IsSimpleType())
            {
                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiDictionary())
            {
                schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiArray())
            {
                schema.Type = "array";
                schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            var allProperties = type.IsInterface
                                    ? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
                                    : type.GetProperties();
            var properties = allProperties.Where(p => !p.ExistsCustomAttribute<JsonIgnoreAttribute>());

            var retVal = new Dictionary<string, OpenApiSchema>();
            foreach (var property in properties)
            {
                var visiblity = property.GetCustomAttribute<OpenApiSchemaVisibilityAttribute>(inherit: false);
                var propertyName = property.GetJsonPropertyName(namingStrategy);

                var ts = property.DeclaringType.GetGenericArguments();
                if (!ts.Any())
                {
                    if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                        retVal.AddRange(recur1);

                        var enumReference = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema() { Reference = enumReference };
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }
                    else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
                    {
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                    }
                    else if (property.PropertyType.IsOpenApiDictionary())
                    {
                        var elementType = property.PropertyType.GetGenericArguments()[1];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                        }
                        else
                        {
                            var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                            retVal.AddRange(recur1);

                            var elementReference = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id = elementType.GetOpenApiReferenceId(false, false)
                            };

                            var dictionarySchema = new OpenApiSchema()
                            {
                                Type = "object",
                                AdditionalProperties = new OpenApiSchema() { Reference = elementReference }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
                        }
                    }
                    else if (property.PropertyType.IsOpenApiArray())
                    {
                        var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                        }
                        else
                        {
                            var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                            retVal.AddRange(elementReference);

                            var reference1 = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id = elementType.GetOpenApiReferenceId(false, false)
                            };
                            var arraySchema = new OpenApiSchema()
                            {
                                Type = "array",
                                Items = new OpenApiSchema()
                                {
                                    Reference = reference1
                                }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
                        }

                    }
                    else
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                        retVal.AddRange(recur1);

                        var reference1 = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema() { Reference = reference1 };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }

                    continue;
                }

                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id = property.PropertyType.GetOpenApiRootReferenceId()
                };

                var referenceSchema = new OpenApiSchema() { Reference = reference };

                if (!ts.Contains(property.PropertyType))
                {
                    if (property.PropertyType.IsOpenApiDictionary())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
                        var dictionarySchema = new OpenApiSchema()
                        {
                            Type = "object",
                            AdditionalProperties = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;

                        continue;
                    }

                    if (property.PropertyType.IsOpenApiArray())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
                        var arraySchema = new OpenApiSchema()
                        {
                            Type = "array",
                            Items = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;

                        continue;
                    }

                    schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;

                    continue;
                }

                schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
            }

            retVal[schemeName] = schema;

            return retVal;
        }

19 Source : TypeExtensions.cs
with MIT License
from aliencube

public static Type GetOpenApiSubType(this Type type)
        {
            if (type.IsDictionaryType())
            {
                return type.GetGenericArguments()[1];
            }

            if (type.BaseType == typeof(Array))
            {
                return type.GetElementType();
            }

            if (type.IsArrayType())
            {
                return type.GetGenericArguments()[0];
            }

            return null;
        }

19 Source : TypeExtensions.cs
with MIT License
from aliencube

public static string GetOpenApiSubTypeName(this Type type, NamingStrategy namingStrategy = null)
        {
            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (type.IsDictionaryType())
            {
                var name = type.GetGenericArguments()[1].Name;

                return namingStrategy.GetPropertyName(name, hreplacedpecifiedName: false);
            }

            if (type.BaseType == typeof(Array))
            {
                var name = type.GetElementType().Name;

                return namingStrategy.GetPropertyName(name, hreplacedpecifiedName: false);
            }

            if (type.IsArrayType())
            {
                var name = type.GetGenericArguments()[0].Name;

                return namingStrategy.GetPropertyName(name, hreplacedpecifiedName: false);
            }

            return null;
        }

19 Source : TypeExtensions.cs
with MIT License
from aliencube

public static string GetOpenApiSubTypeNames(this Type type)
        {
            if (!type.IsGenericType)
            {
                return null;
            }

            var types = type.GetGenericArguments().ToList();
            if (types.Count == 1)
            {
                return types[0].GetOpenApiGenericRootName();
            }

            var names = (string)null;
            for (var i = 0; i < types.Count - 1; i++)
            {
                names += $"{types[i].GetOpenApiGenericRootName()}, ";
            }
            names += $"and {types[types.Count - 1].GetOpenApiGenericRootName()}";

            return names;
        }

19 Source : TypeExtensions.cs
with MIT License
from aliencube

public static Type GetUnderlyingType(this Type type)
        {
            var underlyingType = default(Type);
            if (type.IsOpenApiNullable(out var nullableUnderlyingType))
            {
                underlyingType = nullableUnderlyingType;
            }

            if (type.IsOpenApiArray())
            {
                underlyingType = type.GetElementType() ?? type.GetGenericArguments()[0];
            }

            if (type.IsOpenApiDictionary())
            {
                underlyingType = type.GetGenericArguments()[1];
            }

            if (underlyingType.IsNullOrDefault())
            {
                return underlyingType;
            }

            if (underlyingType.IsGenericType)
            {
                var underlyingTypeOfUnderlyingType = underlyingType.GetUnderlyingType();
                underlyingType = underlyingTypeOfUnderlyingType;
            }

            return underlyingType;
        }

19 Source : AopJsonParser.cs
with Apache License 2.0
from alipay

private static Dictionary<string, AopAttribute> GetAopAttributes(Type type)
        {
            Dictionary<string, AopAttribute> tas = null;
            bool inc = attrs.TryGetValue(type.FullName, out tas);

            if (inc && tas != null) // 从缓存中获取类属性元数据
            {
                return tas;
            }
            else // 创建新的类属性元数据缓存
            {
                tas = new Dictionary<string, AopAttribute>();
            }

            PropertyInfo[] pis = type.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                AopAttribute ta = new AopAttribute();
                ta.Method = pi.GetSetMethod();

                // 获取对象属性名称
                XmlElementAttribute[] xeas = pi.GetCustomAttributes(typeof(XmlElementAttribute), true) as XmlElementAttribute[];
                if (xeas != null && xeas.Length > 0)
                {
                    ta.ItemName = xeas[0].ElementName;
                }

                // 获取列表属性名称
                if (ta.ItemName == null)
                {
                    XmlArrayItemAttribute[] xaias = pi.GetCustomAttributes(typeof(XmlArrayItemAttribute), true) as XmlArrayItemAttribute[];
                    if (xaias != null && xaias.Length > 0)
                    {
                        ta.ItemName = xaias[0].ElementName;
                    }
                    XmlArrayAttribute[] xaas = pi.GetCustomAttributes(typeof(XmlArrayAttribute), true) as XmlArrayAttribute[];
                    if (xaas != null && xaas.Length > 0)
                    {
                        ta.ListName = xaas[0].ElementName;
                    }
                    if (ta.ListName == null)
                    {
                        continue;
                    }
                }

                // 获取属性类型
                if (pi.PropertyType.IsGenericType)
                {
                    Type[] types = pi.PropertyType.GetGenericArguments();
                    ta.ListType = types[0];
                }
                else
                {
                    ta.ItemType = pi.PropertyType;
                }

                tas.Add(pi.Name + ta.ItemType + ta.ListType, ta);
            }

            attrs[type.FullName] = tas;
            return tas;
        }

19 Source : EditorUI.cs
with MIT License
from allenwp

static unsafe void SubmitFieldPropertyInspector(FieldPropertyListInfo info, object enreplacedyComponent, bool showMidi = true)
        {
            ImGui.PushID(GetIdString(info, enreplacedyComponent));

            EditorHelper.RangeAttribute rangeAttribute = null;
            if (info.MemberInfo != null)
            {
                rangeAttribute = CustomAttributeExtensions.GetCustomAttribute<EditorHelper.RangeAttribute>(info.MemberInfo, true);
            }

            var infoType = info.FieldPropertyType;
            if (infoType == typeof(string))
            {
                string val = (string)info.GetValue();
                if (val == null)
                {
                    val = string.Empty;
                }
                if (ImGui.InputText(info.Name, ref val, 1000))
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(bool))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Button);

                bool val = (bool)info.GetValue();
                if (ImGui.Checkbox(info.Name, ref val))
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(float))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                float val = (float)info.GetValue();
                bool result;
                if (rangeAttribute != null
                    && (rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Float
                        || rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int))
                {
                    if (rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Float)
                    {
                        result = ImGui.SliderFloat(info.Name, ref val, rangeAttribute.MinFloat, rangeAttribute.MaxFloat);
                    }
                    else
                    {
                        result = ImGui.SliderFloat(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
                    }
                }
                else
                {
                    result = ImGui.DragFloat(info.Name, ref val, 0.1f);
                }
                if (result)
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(Vector2))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Vector2 val = (Vector2)info.GetValue();
                if (ImGui.DragFloat2(info.Name, ref val))
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(Vector3))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Vector3 val = (Vector3)info.GetValue();
                if (ImGui.DragFloat3(info.Name, ref val))
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(Vector4))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Vector4 val = (Vector4)info.GetValue();
                if (ImGui.DragFloat4(info.Name, ref val))
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(Xna.Vector2))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Xna.Vector2 xnaVal = (Xna.Vector2)info.GetValue();
                Vector2 val = new Vector2(xnaVal.X, xnaVal.Y);
                if (ImGui.DragFloat2(info.Name, ref val))
                {
                    xnaVal.X = val.X;
                    xnaVal.Y = val.Y;
                    info.SetValue(xnaVal);
                }
            }
            else if (infoType == typeof(Xna.Vector3))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Xna.Vector3 xnaVal = (Xna.Vector3)info.GetValue();
                Vector3 val = new Vector3(xnaVal.X, xnaVal.Y, xnaVal.Z);
                if (ImGui.DragFloat3(info.Name, ref val))
                {
                    xnaVal.X = val.X;
                    xnaVal.Y = val.Y;
                    xnaVal.Z = val.Z;
                    info.SetValue(xnaVal);
                }
            }
            else if (infoType == typeof(Xna.Vector4))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                Xna.Vector4 xnaVal = (Xna.Vector4)info.GetValue();
                Vector4 val = new Vector4(xnaVal.X, xnaVal.Y, xnaVal.Z, xnaVal.W);
                if (ImGui.DragFloat4(info.Name, ref val))
                {
                    xnaVal.X = val.X;
                    xnaVal.Y = val.Y;
                    xnaVal.Z = val.Z;
                    xnaVal.W = val.W;
                    info.SetValue(xnaVal);
                }
            }
            else if (infoType == typeof(int))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                int val = (int)info.GetValue();
                bool result;
                if (rangeAttribute != null && rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int)
                {
                    result = ImGui.SliderInt(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
                }
                else
                {
                    result = ImGui.InputInt(info.Name, ref val);
                }
                if (result)
                {
                    info.SetValue(val);
                }
            }
            else if (infoType == typeof(uint))
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);

                int val = (int)((uint)info.GetValue());
                bool result;
                if (rangeAttribute != null && rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int)
                {
                    result = ImGui.SliderInt(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
                }
                else
                {
                    result = ImGui.InputInt(info.Name, ref val);
                }
                if (result)
                {
                    if (val < 0)
                    {
                        val = 0;
                    }
                    info.SetValue((uint)val);
                }
            }
            else if (infoType.IsEnum)
            {
                if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Button);

                var val = info.GetValue();
                var enumNames = infoType.GetEnumNames();
                int currentIndex = 0;
                for (int i = 0; i < enumNames.Length; i++)
                {
                    if (enumNames[i] == val.ToString())
                    {
                        currentIndex = i;
                    }
                }
                if (ImGui.Combo(info.Name, ref currentIndex, enumNames, enumNames.Length))
                {
                    info.SetValue(infoType.GetEnumValues().GetValue(currentIndex));
                }
            }
            else if (typeof(IList).IsreplacedignableFrom(infoType))
            {
                var listthing = info.GetValue();
                IList list = listthing as IList;
                ImGui.Text($"{info.Name} List ({list.Count} items)");
                ImGui.SameLine();
                if (ImGui.Button("-"))
                {
                    if (list.Count > 0)
                    {
                        list.RemoveAt(list.Count - 1);
                    }
                }
                ImGui.SameLine();
                if (ImGui.Button("+"))
                {
                    Type lisreplacedemType = list.GetType().GetGenericArguments().First();
                    if (lisreplacedemType.IsValueType)
                    {
                        list.Add(Activator.CreateInstance(lisreplacedemType));
                    }
                    else
                    {
                        list.Add(null);
                    }
                }

                ImGui.Indent();
                for (int i = 0; i < list.Count; i++)
                {
                    FieldPropertyListInfo itemInfo = new FieldPropertyListInfo(list, i);
                    SubmitFieldPropertyInspector(itemInfo, list);
                }
                ImGui.Unindent();
            }
            else if (!infoType.IsValueType)
            {
                string valText;
                var value = info.GetValue();
                if (value != null)
                {
                    valText = value.ToString();
                }
                else
                {
                    valText = "null";
                }
                string label = $"{info.Name}: {valText}";
                if (typeof(Component).IsreplacedignableFrom(infoType) || typeof(Enreplacedy).IsreplacedignableFrom(infoType))
                {
                    if (ImGui.Selectable(label, false))
                    {
                        SelectedEnreplacedyComponent = value;
                        scrollEnreplacediesView = true;
                        scrollSceneGraphView = true;
                    }
                }
                else
                {
                    ImGui.Text(label);
                }

                if (draggedObject != null && infoType.IsreplacedignableFrom(draggedObject.GetType()))
                {
                    if (ImGui.BeginDragDropTarget())
                    {
                        var payload = ImGui.AcceptDragDropPayload(PAYLOAD_STRING);
                        if (payload.NativePtr != null) // Only when this is non-null does it mean that we've released the drag
                        {
                            info.SetValue(draggedObject);
                            draggedObject = null;
                        }
                        ImGui.EndDragDropTarget();
                    }
                }
            }
            else
            {
                SubmitReadonlyFieldPropertyInspector(info);
            }
            ImGui.PopID();

            SubmitHelpMarker(info);
        }

19 Source : TypeExtensions.cs
with MIT License
from allisterb

public static Type GetUnderlyingType(this Type type)
        {
            if (type == null) throw new ArgumentNullException("type");

            if (type.IsNullable())
                type = type.GetGenericArguments()[0];

            if (type.IsEnum)
                type = Enum.GetUnderlyingType(type);

            return type;
        }

19 Source : TypeExtensions.cs
with MIT License
from allisterb

public static Type TranslateGenericParameters(this Type type, Type[] typeArguments)
        {
            // 'T paramName' case
            //
            if (type.IsGenericParameter)
                return typeArguments[type.GenericParameterPosition];

            // 'List<T> paramName' or something like that.
            //
            if (type.IsGenericType && type.ContainsGenericParameters)
            {
                Type[] genArgs = type.GetGenericArguments();

                for (int i = 0; i < genArgs.Length; ++i)
                    genArgs[i] = TranslateGenericParameters(genArgs[i], typeArguments);

                return type.GetGenericTypeDefinition().MakeGenericType(genArgs);
            }

            // Non-generic type.
            //
            return type;
        }

19 Source : HttpContextUtility.cs
with MIT License
from AlphaYu

public static HttpContext GetCurrentHttpContext()
        {
            var asyncLocal = (_asyncLocalAccessor ??= CreateAsyncLocalAccessor())();
            if (asyncLocal == null)
            {
                return null;
            }

            var holder = (_holderAccessor ??= CreateHolderAccessor(asyncLocal))(asyncLocal);
            if (holder == null)
            {
                return null;
            }

            return (_httpContextAccessor ??= CreateHttpContextAccessor(holder))(holder);

            static Func<object> CreateAsyncLocalAccessor()
            {
                var fieldInfo = typeof(HttpContextAccessor).GetField("_httpContextCurrent", BindingFlags.Static | BindingFlags.NonPublic);
                var field = Expression.Field(null, fieldInfo);
                return Expression.Lambda<Func<object>>(field).Compile();
            }

            static Func<object, object> CreateHolderAccessor(object asyncLocal)
            {
                var holderType = asyncLocal.GetType().GetGenericArguments()[0];
                var method = typeof(AsyncLocal<>).MakeGenericType(holderType).GetProperty("Value").GetGetMethod();
                var target = Expression.Parameter(typeof(object));
                var convert = Expression.Convert(target, asyncLocal.GetType());
                var getValue = Expression.Call(convert, method);
                return Expression.Lambda<Func<object, object>>(getValue, target).Compile();
            }

            static Func<object, HttpContext> CreateHttpContextAccessor(object holder)
            {
                var target = Expression.Parameter(typeof(object));
                var convert = Expression.Convert(target, holder.GetType());
                var field = Expression.Field(convert, "Context");
                var convertAsResult = Expression.Convert(field, typeof(HttpContext));
                return Expression.Lambda<Func<object, HttpContext>>(convertAsResult, target).Compile();
            }
        }

19 Source : HlslMappings.cs
with MIT License
from Aminator

public static string GetMappedName(Type type)
        {
            type = type.GetElementType() ?? type;

            string? typeNameFromAttribute = GetTypeNameFromAttribute(type);
            string fullTypeName = typeNameFromAttribute ?? type.FullName;

            string mappedName = knownTypes.TryGetValue(fullTypeName, out string mapped) ? mapped : fullTypeName.Replace(".", "::");

            return type.IsGenericType ? mappedName + $"<{string.Join(", ", type.GetGenericArguments().Select(t => GetMappedName(t)))}>" : mappedName;
        }

19 Source : ControlExample.cs
with MIT License
from amwx

protected string ResolveType(Type t)
		{
			if (t.IsGenericType)
			{
				var genType = t.GetGenericTypeDefinition().Name;
				genType = genType.Substring(0, genType.IndexOf('`'));
				var args = t.GetGenericArguments().Select(x => ResolveType(x)).ToArray();

				if (genType.Equals("Nullable", StringComparison.OrdinalIgnoreCase))
				{
					return $"{args[0]}?";
				}
				else
				{
					return $"{genType}<{string.Join(',', args)}>";
				}				
			}
			else
			{
				if (t == typeof(object))
					return "object";
				else if (t == typeof(string))
					return "string";
				else if (t == typeof(bool))
					return "bool";
				else if (t == typeof(char))
					return "char";
				else if (t == typeof(int))
					return "int";
				else if (t == typeof(float))
					return "float";
				else if (t == typeof(double))
					return "double";
				else if (t == typeof(long))
					return "long";
				else if (t == typeof(ulong))
					return "ulong";
				else if (t == typeof(uint))
					return "uint";
				else if (t == typeof(byte))
					return "byte";
				else if (t == typeof(short))
					return "short";
				else if (t == typeof(decimal))
					return "decimal";
				else if (t == typeof(void))
					return "void";

				return t.Name;
			}
		}

19 Source : DictionaryStringKeyPreserveCasingConverter.cs
with Apache License 2.0
from Anapher

private static bool IsStringDictionary(Type givenType)
        {
            var interfaceTypes = givenType.GetInterfaces();
            return interfaceTypes.Any(x =>
                x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) &&
                x.GetGenericArguments()[0] == typeof(string));
        }

19 Source : UniqueSettingsCollectionMarhalerFactory.cs
with GNU General Public License v3.0
from AndreiFedarets

private static Type GetSettingsType(Type type)
        {
            while (type != null)
            {
                if (type.IsGenericType &&
                    type.GetGenericTypeDefinition() == typeof(UniqueSettingsCollection<>))
                {
                    return type.GetGenericArguments()[0];
                }
                type = type.BaseType;
            }
            return null;
        }

19 Source : ModelNameHelper.cs
with GNU General Public License v3.0
from andysal

public static string GetModelName(Type type)
        {
            ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
            if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))
            {
                return modelNameAttribute.Name;
            }

            string modelName = type.Name;
            if (type.IsGenericType)
            {
                // Format the generic type name to something like: GenericOreplacedurment1AndArgument2
                Type genericType = type.GetGenericTypeDefinition();
                Type[] genericArguments = type.GetGenericArguments();
                string genericTypeName = genericType.Name;

                // Trim the generic parameter counts from the name
                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
                string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
                modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));
            }

            return modelName;
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
        {
            Type type = nullableType.GetGenericArguments()[0];
            ObjectGenerator objectGenerator = new ObjectGenerator();
            return objectGenerator.GenerateObject(type, createdObjectReferences);
        }

19 Source : XmlDocumentationProvider.cs
with GNU General Public License v3.0
from andysal

private static string GetTypeName(Type type)
        {
            string name = type.FullName;
            if (type.IsGenericType)
            {
                // Format the generic type name to something like: Generic{System.Int32,System.String}
                Type genericType = type.GetGenericTypeDefinition();
                Type[] genericArguments = type.GetGenericArguments();
                string genericTypeName = genericType.FullName;

                // Trim the generic parameter counts from the name
                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
                string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
                name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames));
            }
            if (type.IsNested)
            {
                // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML doreplacedentation syntax.
                name = name.Replace("+", ".");
            }

            return name;
        }

19 Source : CsvOutputFormatter.cs
with GNU General Public License v3.0
from andysal

private void writeStream(Type type, object value, Stream stream)
        {
            Type itemType = type.GetGenericArguments()[0];

            StringWriter _stringWriter = new StringWriter();

            _stringWriter.WriteLine(
                string.Join<string>(
                    ";", itemType.GetProperties().Select(x => x.Name)
                )
            );

            foreach (var obj in (IEnumerable<object>)value)
            {

                var vals = obj.GetType().GetProperties().Select(
                    pi => new {
                        Value = pi.GetValue(obj, null)
                    }
                );

                string _valueLine = string.Empty;

                foreach (var val in vals)
                {

                    if (val.Value != null)
                    {

                        var _val = val.Value.ToString();

                        //Check if the value contans a comma and place it in quotes if so
                        if (_val.Contains(","))
                            _val = string.Concat("\"", _val, "\"");

                        //Replace any \r or \n special characters from a new line with a space
                        if (_val.Contains("\r"))
                            _val = _val.Replace("\r", " ");
                        if (_val.Contains("\n"))
                            _val = _val.Replace("\n", " ");

                        _valueLine = string.Concat(_valueLine, _val, ";");

                    }
                    else
                    {

                        _valueLine = string.Concat(string.Empty, ";");
                    }
                }

                _stringWriter.WriteLine(_valueLine.TrimEnd(';'));
            }

            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(_stringWriter.ToString());
            streamWriter.Flush();
        }

19 Source : ModelDescriptionGenerator.cs
with GNU General Public License v3.0
from andysal

public ModelDescription GetOrCreateModelDescription(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            Type underlyingType = Nullable.GetUnderlyingType(modelType);
            if (underlyingType != null)
            {
                modelType = underlyingType;
            }

            ModelDescription modelDescription;
            string modelName = ModelNameHelper.GetModelName(modelType);
            if (GeneratedModels.TryGetValue(modelName, out modelDescription))
            {
                if (modelType != modelDescription.ModelType)
                {
                    throw new InvalidOperationException(
                        String.Format(
                            CultureInfo.CurrentCulture,
                            "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
                            "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
                            modelName,
                            modelDescription.ModelType.FullName,
                            modelType.FullName));
                }

                return modelDescription;
            }

            if (DefaultTypeDoreplacedentation.ContainsKey(modelType))
            {
                return GenerateSimpleTypeModelDescription(modelType);
            }

            if (modelType.IsEnum)
            {
                return GenerateEnumTypeModelDescription(modelType);
            }

            if (modelType.IsGenericType)
            {
                Type[] genericArguments = modelType.GetGenericArguments();

                if (genericArguments.Length == 1)
                {
                    Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
                    if (enumerableType.IsreplacedignableFrom(modelType))
                    {
                        return GenerateCollectionModelDescription(modelType, genericArguments[0]);
                    }
                }
                if (genericArguments.Length == 2)
                {
                    Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
                    if (dictionaryType.IsreplacedignableFrom(modelType))
                    {
                        return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
                    }

                    Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
                    if (keyValuePairType.IsreplacedignableFrom(modelType))
                    {
                        return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
                    }
                }
            }

            if (modelType.IsArray)
            {
                Type elementType = modelType.GetElementType();
                return GenerateCollectionModelDescription(modelType, elementType);
            }

            if (modelType == typeof(NameValueCollection))
            {
                return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
            }

            if (typeof(IDictionary).IsreplacedignableFrom(modelType))
            {
                return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
            }

            if (typeof(IEnumerable).IsreplacedignableFrom(modelType))
            {
                return GenerateCollectionModelDescription(modelType, typeof(object));
            }

            return GenerateComplexTypeModelDescription(modelType);
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
        {
            Type genericTypeDefinition = type.GetGenericTypeDefinition();
            if (genericTypeDefinition == typeof(Nullable<>))
            {
                return GenerateNullable(type, createdObjectReferences);
            }

            if (genericTypeDefinition == typeof(KeyValuePair<,>))
            {
                return GenerateKeyValuePair(type, createdObjectReferences);
            }

            if (IsTuple(genericTypeDefinition))
            {
                return GenerateTuple(type, createdObjectReferences);
            }

            Type[] genericArguments = type.GetGenericArguments();
            if (genericArguments.Length == 1)
            {
                if (genericTypeDefinition == typeof(IList<>) ||
                    genericTypeDefinition == typeof(IEnumerable<>) ||
                    genericTypeDefinition == typeof(ICollection<>))
                {
                    Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
                    return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
                }

                if (genericTypeDefinition == typeof(IQueryable<>))
                {
                    return GenerateQueryable(type, collectionSize, createdObjectReferences);
                }

                Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
                if (closedCollectionType.IsreplacedignableFrom(type))
                {
                    return GenerateCollection(type, collectionSize, createdObjectReferences);
                }
            }

            if (genericArguments.Length == 2)
            {
                if (genericTypeDefinition == typeof(IDictionary<,>))
                {
                    Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
                    return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
                }

                Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
                if (closedDictionaryType.IsreplacedignableFrom(type))
                {
                    return GenerateDictionary(type, collectionSize, createdObjectReferences);
                }
            }

            if (type.IsPublic || type.IsNestedPublic)
            {
                return GenerateComplexObject(type, createdObjectReferences);
            }

            return null;
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
        {
            Type[] genericArgs = type.GetGenericArguments();
            object[] parameterValues = new object[genericArgs.Length];
            bool failedToCreateTuple = true;
            ObjectGenerator objectGenerator = new ObjectGenerator();
            for (int i = 0; i < genericArgs.Length; i++)
            {
                parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
                failedToCreateTuple &= parameterValues[i] == null;
            }
            if (failedToCreateTuple)
            {
                return null;
            }
            object result = Activator.CreateInstance(type, parameterValues);
            return result;
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
        {
            Type[] genericArgs = keyValuePairType.GetGenericArguments();
            Type typeK = genericArgs[0];
            Type typeV = genericArgs[1];
            ObjectGenerator objectGenerator = new ObjectGenerator();
            object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
            object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
            if (keyObject == null && valueObject == null)
            {
                // Failed to create key and values
                return null;
            }
            object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
            return result;
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
        {
            Type typeK = typeof(object);
            Type typeV = typeof(object);
            if (dictionaryType.IsGenericType)
            {
                Type[] genericArgs = dictionaryType.GetGenericArguments();
                typeK = genericArgs[0];
                typeV = genericArgs[1];
            }

            object result = Activator.CreateInstance(dictionaryType);
            MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
            MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
            ObjectGenerator objectGenerator = new ObjectGenerator();
            for (int i = 0; i < size; i++)
            {
                object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
                if (newKey == null)
                {
                    // Cannot generate a valid key
                    return null;
                }

                bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
                if (!containsKey)
                {
                    object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
                    addMethod.Invoke(result, new object[] { newKey, newValue });
                }
            }

            return result;
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
        {
            bool isGeneric = queryableType.IsGenericType;
            object list;
            if (isGeneric)
            {
                Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
                list = GenerateCollection(listType, size, createdObjectReferences);
            }
            else
            {
                list = GenerateArray(typeof(object[]), size, createdObjectReferences);
            }
            if (list == null)
            {
                return null;
            }
            if (isGeneric)
            {
                Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
                MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
                return asQueryableMethod.Invoke(null, new[] { list });
            }

            return Queryable.AsQueryable((IEnumerable)list);
        }

19 Source : ObjectGenerator.cs
with GNU General Public License v3.0
from andysal

private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
        {
            Type type = collectionType.IsGenericType ?
                collectionType.GetGenericArguments()[0] :
                typeof(object);
            object result = Activator.CreateInstance(collectionType);
            MethodInfo addMethod = collectionType.GetMethod("Add");
            bool areAllElementsNull = true;
            ObjectGenerator objectGenerator = new ObjectGenerator();
            for (int i = 0; i < size; i++)
            {
                object element = objectGenerator.GenerateObject(type, createdObjectReferences);
                addMethod.Invoke(result, new object[] { element });
                areAllElementsNull &= element == null;
            }

            if (areAllElementsNull)
            {
                return null;
            }

            return result;
        }

See More Examples