当前位置: 首页>>代码示例>>C#>>正文


C# Type.GetGenericArguments方法代码示例

本文整理汇总了C#中System.Type.GetGenericArguments方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetGenericArguments方法的具体用法?C# Type.GetGenericArguments怎么用?C# Type.GetGenericArguments使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Type的用法示例。


在下文中一共展示了Type.GetGenericArguments方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: InferType

        public static IType InferType(Type type, IMetadataContainer container)
        {
            Type genericTypeDefinition = type.GetGenericArguments().Any() ? type.GetGenericTypeDefinition() : type;

            if (typeof(IFunction<,>).IsAssignableFrom(genericTypeDefinition))
            {
                Type left = type.GetGenericArguments()[0];
                Type right = type.GetGenericArguments()[1];
                return new Types.ArrowType(InferType(left, container), InferType(right, container));
            }
            else if (typeof(Either<,>).IsAssignableFrom(genericTypeDefinition))
            {
                Type left = type.GetGenericArguments()[0];
                Type right = type.GetGenericArguments()[1];
                return new Types.SumType(InferType(left, container), InferType(right, container));
            }
            else if (typeof(Tuple<,>).IsAssignableFrom(genericTypeDefinition))
            {
                Type left = type.GetGenericArguments()[0];
                Type right = type.GetGenericArguments()[1];
                return new Types.ProductType(InferType(left, container), InferType(right, container));
            }
            else if (type.IsGenericParameter)
            {
                return new Types.TypeParameter(type.Name);
            }
            else
            {
                container.ResolveType(type.Name);
                var genericParameters = type.GetGenericArguments().Select(t => InferType(t, container)).ToArray();
                return new Types.TypeSynonym(type.Name, genericParameters);
            }
        }
开发者ID:paf31,项目名称:Purity,代码行数:33,代码来源:ReflectionUtilities.cs

示例2: Populate

        public object Populate(string propertyName, Type propertyType, object currentValue, int depth, Func<int, string, Type, object, PropertyInfo, object> populateKey, Func<int, string, Type, object, PropertyInfo, object> populateValue)
        {
            if (currentValue != null && ((IDictionary)currentValue).Count > 0)
            {
                return currentValue;
            }

            IDictionary newDictionary;

            if (currentValue != null && ((IDictionary)currentValue).Count == 0)
            {
                newDictionary = (IDictionary)currentValue;
            }
            else
            {
                newDictionary = (IDictionary)Activator.CreateInstance(propertyType);
            }

            for (var i = 0; i < AutoBuilderConfiguration.DefaultCollectionItemCount; i++)
            {
                newDictionary.Add(populateKey(depth + 1, propertyName, propertyType.GetGenericArguments()[0], null, null), populateValue(depth + 1, propertyName, propertyType.GetGenericArguments()[1], null, null));
            }

            return newDictionary;
        }
开发者ID:fir3pho3nixx,项目名称:NAuto,代码行数:25,代码来源:PopulateDictionaryService.cs

示例3: DictionaryJsonSerializer

        private DictionaryJsonSerializer(Type type, bool encrypt, JsonMappings mappings, bool shouldUseAttributeDefinedInInterface)
        {
            _encrypt = encrypt;
            _mappings = mappings;
            _shouldUseAttributeDefinedInInterface = shouldUseAttributeDefinedInInterface;

            Type keyType;

            if (type.IsAssignableToGenericIDictionary())
            {
                var genericArguments = type.GetGenericArguments();
                keyType = genericArguments[0];

                if (typeof(IDictionary<string, object>).IsAssignableFrom(type))
                {
                    _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
                    _write = GetIDictionaryOfStringToObjectWriteAction();
                }
                else if (type.IsAssignableToGenericIDictionaryOfStringToAnything())
                {
                    _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
                    _write = GetIDictionaryOfStringToAnythingWriteAction();
                }
                else
                {
                    _keySerializer = JsonSerializerFactory.GetSerializer(genericArguments[0], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
                    _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
                    _write = GetIDictionaryOfAnythingToAnythingWriteAction();
                }
            }
            else
            {
                keyType = typeof(object);

                _keySerializer = JsonSerializerFactory.GetSerializer(typeof(object), _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
                _valueSerializer = _keySerializer;
                _write = GetIDictionaryOfAnythingToAnythingWriteAction();
            }

            if (type.IsInterface)
            {
                if (type.IsGenericIDictionary())
                {
                    type = typeof(Dictionary<,>).MakeGenericType(
                        type.GetGenericArguments()[0], type.GetGenericArguments()[1]);
                }
                else if (type == typeof(IDictionary))
                {
                    type = typeof(Dictionary<object, object>);
                }
                else
                {
                    throw new NotSupportedException(type.FullName);
                }
            }

            _createDictionary = GetCreateDictionaryFunc(type);
            _deserializeKey = GetDeserializeKeyFunc(keyType);
            _addToDictionary = GetAddToDictionaryAction(type);
        }
开发者ID:QuickenLoans,项目名称:XSerializer,代码行数:60,代码来源:DictionaryJsonSerializer.cs

示例4: CanParseType

 public virtual bool CanParseType(Type type)
 {
     return
         type.IsKeyValuePairType() &&
         StringParsing.GetParser(type.GetGenericArguments()[0]) != null &&
         StringParsing.GetParser(type.GetGenericArguments()[1]) != null;
 }
开发者ID:bitpantry,项目名称:BitPantry.Parsing.Strings,代码行数:7,代码来源:KeyValuePairParser.cs

示例5: GetFullName

		public static string GetFullName(Type type)
		{
			if (type.IsByRef) return "ref " + GetFullName(type.GetElementType());
			if (type.DeclaringType != null) return GetFullName(type.DeclaringType) + "." + TypeName(type);		
			
			// HACK: Some constructed generic types report a FullName of null
			if (type.FullName == null) 
			{
				string[] argumentNames = Array.ConvertAll<Type, string>(
					type.GetGenericArguments(),
					GetFullName);
				
				return string.Format(
					"{0}[{1}]",
					GetFullName(type.GetGenericTypeDefinition()),
					string.Join(", ", argumentNames));
				
			}
			string name = TypeName(type.FullName);
			if (type.IsGenericTypeDefinition)
			{
				name = string.Format(
					"{0}[of {1}]", 
					name, 
					string.Join(", ", Array.ConvertAll<Type, string>(
						type.GetGenericArguments(), 
						TypeName)));
			}
			return name;
		}
开发者ID:HaKDMoDz,项目名称:GNet,代码行数:30,代码来源:TypeUtilities.cs

示例6: create

            /// <summary>
            /// 生成类定义
            /// </summary>
            /// <param name="type">类型</param>
            /// <param name="isPartial">是否部分定义</param>
            /// <param name="isClass">是否建立类定义</param>
            private void create(Type type, bool isPartial, bool isClass)
            {
                if (type.ReflectedType == null)
                {
                    start.Add("namespace " + type.Namespace + @"
{");
                    end.Add(@"
}");
                }
                else
                {
                    create(type.ReflectedType.IsGenericType ? type.ReflectedType.MakeGenericType(type.GetGenericArguments()) : type.ReflectedType, true, true);
                }
                if (isClass)
                {
                    start.Add(@"
    " + (type.IsPublic ? "public" : null)
              + (type.IsAbstract ? " abstract" : null)
              + (isPartial ? " partial" : null)
              + (type.IsInterface ? " interface" : " class")
              + " " + type.Name + (type.IsGenericType ? "<" + type.GetGenericArguments().joinString(", ", x => x.fullName()) + ">" : null) + @"
    {");
                    end.Add(@"
    }");
                }
            }
开发者ID:khaliyo,项目名称:fastCSharp,代码行数:32,代码来源:cSharper.cs

示例7: GetTypeDefinition

        /// <summary>
        /// Gets a correct type definition for a given type, ready for code generation, since
        /// type.FullName doesnt represent generics in a way to be used in code generation.
        /// Handles generics.
        /// Based on: http://stackoverflow.com/questions/401681/how-can-i-get-the-correct-text-definition-of-a-generic-type-using-reflection
        /// </summary>
        /// <param name="type">the type to get definition for</param>
        /// <returns>the string representation of the type definition</returns>
        public static string GetTypeDefinition(Type type)
        {
            if (type.IsGenericParameter)
            {
                return type.Name;
            }

            if (!type.IsGenericType)
            {
                return type.FullName;
            }

            StringBuilder builder = new StringBuilder();
            string name = type.Name;
            int index = name.IndexOf("`");
            builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));
            builder.Append('<');
            bool first = true;
            for (int i = 0; i < type.GetGenericArguments().Length; i++)
            {
                Type arg = type.GetGenericArguments()[i];
                if (!first)
                {
                    builder.Append(',');
                }
                builder.Append(GetTypeDefinition(arg));
                first = false;
            }
            builder.Append('>');
            return builder.ToString();
        }
开发者ID:varunkumarmnnit,项目名称:otis-lib,代码行数:39,代码来源:TypeHelper.cs

示例8: GetConfigItemValueTypeEnum

 /// <summary>
 /// 获取配置项的值的类型的枚举
 /// </summary>
 /// <param name="valType">配置项值类型</param>
 /// <returns></returns>
 public static string GetConfigItemValueTypeEnum(Type valType)
 {
     //列表
     if (typeof(IList).IsAssignableFrom(valType))
     {
         var genericArguments = valType.GetGenericArguments();
         if (genericArguments.Length == 1 && valType.IsGenericType && genericArguments.First() == typeof(object))
             return ValueTypeEnum.ObjectItemList.ToString();
         return ValueTypeEnum.List.ToString();
     }
     //字典
     if (typeof(IDictionary).IsAssignableFrom(valType))
     {
         var genericArguments = valType.GetGenericArguments();
         if (genericArguments.Length == 2 && genericArguments.First() == typeof(string) && valType.IsGenericType && genericArguments.Last() == typeof(object))
             return ValueTypeEnum.ObjectItemDictionary.ToString();
         return ValueTypeEnum.Dictionary.ToString();
     }
     //基础类型
     if (IsUnderlyingType(valType))
     {
         return ValueTypeEnum.Underlying.ToString();
     }
     //自定义配置实体
     return ValueTypeEnum.Entity.ToString();
 }
开发者ID:yhhno,项目名称:Adhesive,代码行数:31,代码来源:ConfigHelper.cs

示例9: CreateInstance

        /// <summary>
        /// Create a new instance from a Type
        /// </summary>
        public static object CreateInstance(Type type)
        {
            try
            {
                CreateObject c = null;

                if (_cacheCtor.TryGetValue(type, out c))
                {
                    return c();
                }
                else
                {
                    if (type.IsClass)
                    {
                        var dynMethod = new DynamicMethod("_", type, null);
                        var il = dynMethod.GetILGenerator();
                        il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
                        il.Emit(OpCodes.Ret);
                        c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
                        _cacheCtor.Add(type, c);
                    }
                    else if (type.IsInterface) // some know interfaces
                    {
                        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
                        {
                            return CreateInstance(GetGenericListOfType(UnderlyingTypeOf(type)));
                        }
                        else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                        {
                            var k = type.GetGenericArguments()[0];
                            var v = type.GetGenericArguments()[1];
                            return CreateInstance(GetGenericDictionaryOfType(k, v));
                        }
                        else
                        {
                            throw LiteException.InvalidCtor(type);
                        }
                    }
                    else // structs
                    {
                        var dynMethod = new DynamicMethod("_", typeof(object), null);
                        var il = dynMethod.GetILGenerator();
                        var lv = il.DeclareLocal(type);
                        il.Emit(OpCodes.Ldloca_S, lv);
                        il.Emit(OpCodes.Initobj, type);
                        il.Emit(OpCodes.Ldloc_0);
                        il.Emit(OpCodes.Box, type);
                        il.Emit(OpCodes.Ret);
                        c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
                        _cacheCtor.Add(type, c);
                    }

                    return c();
                }
            }
            catch (Exception)
            {
                throw LiteException.InvalidCtor(type);
            }
        }
开发者ID:remcodegroot,项目名称:LiteDB,代码行数:63,代码来源:Reflection.cs

示例10: CreateContract

        protected override JsonContract CreateContract(Type objectType)
        {
            // This class special cases the JsonContract for just the Delta<T> class. All other types should function
            // as usual.
            if (objectType.IsGenericType &&
                objectType.GetGenericTypeDefinition() == typeof(Delta<>) &&
                objectType.GetGenericArguments().Length == 1)
            {
                var contract = CreateDynamicContract(objectType);
                contract.Properties.Clear();

                var underlyingContract = CreateObjectContract(objectType.GetGenericArguments()[0]);
                var underlyingProperties =
                    underlyingContract.CreatedType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var property in underlyingContract.Properties)
                {
                    property.DeclaringType = objectType;
                    property.ValueProvider = new DynamicObjectValueProvider()
                    {
                        PropertyName = this.ResolveName(underlyingProperties, property.PropertyName),
                    };

                    contract.Properties.Add(property);
                }

                return contract;
            }

            return base.CreateContract(objectType);
        }
开发者ID:rajendra1809,项目名称:VirtoCommerce,代码行数:30,代码来源:DeltaContractResolver.cs

示例11: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            var keyType = objectType.GetGenericArguments()[0];
            var keyValueType = keyType.BaseType.GetGenericArguments()[0];
            var valueType = objectType.GetGenericArguments()[1];
            var intermediateDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), valueType);
            var intermediateDictionary = (IDictionary)Activator.CreateInstance(intermediateDictionaryType);
            serializer.Populate(reader, intermediateDictionary);

            var valueProperty = keyType.GetProperty("Value");
            var finalDictionary = (IDictionary)Activator.CreateInstance(objectType);
            foreach (DictionaryEntry pair in intermediateDictionary)
            {
                object value;
                if (keyValueType == typeof(Guid))
                    value = Guid.Parse(pair.Key.ToString());
                else
                    value = Convert.ChangeType(pair.Key, keyValueType, null);

                var key = Activator.CreateInstance(keyType);
                valueProperty.SetValue(key, value, null);
                finalDictionary.Add(key, pair.Value);
            }
            return finalDictionary;
        }
开发者ID:LenFon,项目名称:Bifrost,代码行数:28,代码来源:ConceptDictionaryConverter.cs

示例12: CheckDoesModelTypeMatch

        void CheckDoesModelTypeMatch(Type type, Type modelType)
        {
            if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(View<>))
                {
                    if (modelType == null)
                    {
                        throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed null.", ViewFile, type.GetGenericArguments()[0]));
                    }
                    if (!type.GetGenericArguments()[0].IsAssignableFrom(modelType))
                    {
                        throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed model of type {2}.", ViewFile, type.GetGenericArguments()[0], modelType));
                    }

                    return;
                }
            }

            if (type == typeof(View))
                return;

            // Recurse
            CheckDoesModelTypeMatch(type.BaseType, modelType);
        }
开发者ID:toptensoftware,项目名称:manos,代码行数:25,代码来源:RazorViewTemplate.cs

示例13: DeserializeToDictionary

 private IDictionary DeserializeToDictionary(string input, Type type)
 {
     if (input.StartsWith("{", StringComparison.Ordinal) == true && input.EndsWith("}", StringComparison.Ordinal) == true)
     {
         string source = input;
         input = input.Substring(1, input.Length - 2);
         IDictionary dictionary = Activator.CreateInstance(type, true) as IDictionary;
         // 获取键类型。
         Type keyType = type.GetGenericArguments()[0];
         // 获取值类型。
         Type valueType = type.GetGenericArguments()[1];
         foreach (var temp in JsonHelper.ItemReader(input))
         {
             string key;
             string value;
             JsonHelper.ItemSpliter(temp, out key, out value);
             object oKey = DeserializeToObject(key, keyType);
             if (dictionary.Contains(oKey) == false)
             {
                 object oValue = DeserializeToObject(value, valueType);
                 dictionary.Add(oKey, oValue);
             }
             else
             {
                 throw new JsonDeserializeException(source, type);
             }
         }
         return dictionary;
     }
     else
     {
         throw new JsonDeserializeException(input, type);
     }
 }
开发者ID:h82258652,项目名称:Common,代码行数:34,代码来源:JsonDeserializer.Dictionary.cs

示例14: IsProperInterface

 private bool IsProperInterface(Type candidateInterface, Type openGenericInterfaceType, Type commandType)
 {
     return candidateInterface.IsGenericType &&
            candidateInterface.GetGenericTypeDefinition() == openGenericInterfaceType &&
            candidateInterface.GetGenericArguments().Length == 1 &&
            MatchesType(candidateInterface.GetGenericArguments()[0], commandType);
 }
开发者ID:SzymonPobiega,项目名称:LeanCommandUnframework,代码行数:7,代码来源:TypeSelector.cs

示例15: TestAndAddRecursive

        public static void TestAndAddRecursive(Type type,  String declaringTypeNamespace, List<Type> valueTypes, List<String> namespaces)
        {
            if (type.IsGenericType)
            {
                if (type.GetGenericArguments() != null)
                {
                    foreach (var genericArg in type.GetGenericArguments())
                    {
                        TestAndAddRecursive(genericArg, declaringTypeNamespace, valueTypes, namespaces);
                    }
                }
                return;
            }

            if (IsValueTypeNoEnumOrPrimitve(type) && !valueTypes.Contains(type) && 
                type.Namespace != "System" && type.Namespace != declaringTypeNamespace)
            {
                valueTypes.Add(type);
            }

            if (!IsValueTypeNoEnumOrPrimitve(type) && type.Namespace != declaringTypeNamespace)
            {
                if (!ExcludedExternalNamespaces.Contains(type.Namespace) && !namespaces.Contains(type.Namespace))
                {
                    namespaces.Add(type.Namespace);
                }
                else if (type.Namespace == "System" && type.Name == "Uri" && !namespaces.Contains("Windows.Foundation")) // Uri is special..
                {
                    namespaces.Add("Windows.Foundation");
                }
            }
        }
开发者ID:pacificIT,项目名称:NodeRT,代码行数:32,代码来源:ExternalTypesHelper.cs


注:本文中的System.Type.GetGenericArguments方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。