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


C# Type.MakeGenericType方法代码示例

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


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

示例1: TestConstructorArgumentsNullCombinations

        public static void TestConstructorArgumentsNullCombinations(Type testedType, Type[] typeArguments, IList<Func<object>> arguments)
        {
            if (testedType.IsGenericType)
            {
                testedType = testedType.MakeGenericType(typeArguments);
            }

            var argumentTypes = arguments.Select(argument => argument.Method.ReturnType).ToArray();
            var constructor = testedType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, argumentTypes, null);

            if (constructor == null)
            {
                throw new ArgumentException("Constructor could not be found");
            }

            for (int i = 0; i < arguments.Count; i++)
            {
                object[] args = arguments.Select(a => a()).ToArray();
                args[i] = null;

                Assert.That(() =>
                {
                    try
                    {
                        constructor.Invoke(args);
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw exception.InnerException;
                    }
                }, Throws.TypeOf<ArgumentNullException>());
            }
        }
开发者ID:tomastauer,项目名称:Tauco.Dicom,代码行数:33,代码来源:TestUtilities.cs

示例2: InitializeContext

        public static void InitializeContext(this IHostedApplication hostedApplication, Type configurationType, Type databaseInitializerType, Type databaseContainerType)
        {
            try
            {
                if (hostedApplication.IsNull())
                    throw new ArgumentNullException("hostedApplication");

                var context = hostedApplication.CreateApplicationContext(configurationType);

                if (hostedApplication.HasMigrationConfigurationType())
                {
                    Type migType = databaseInitializerType.MakeGenericType(hostedApplication.ApplicationContextType, context.GetType());
                    var migration = System.Activator.CreateInstance(migType);

                    var mi = databaseContainerType.GetMethods().Where(a => a.Name == "SetInitializer" && a.GetGenericArguments().Length == 1).FirstOrDefault();
                    var method = mi.MakeGenericMethod(hostedApplication.ApplicationContextType);

                    method.Invoke(null, new[] { migration });
                }
            }
            catch (Exception ex)
            {
                throw new System.Data.EntityException("Error Initializing Hosted Application", ex);
            }
        }
开发者ID:priestofpsi,项目名称:theDiary-Common-Framework,代码行数:25,代码来源:Extensions.HostingApplication.cs

示例3: NewExpr

 internal static Expression NewExpr(this Type baseType, Type ifInterfaceType)
 {
     var newExpr = baseType.IsInterface()
         ? New(ifInterfaceType.MakeGenericType(TypeHelper.GetElementTypes(baseType, ElemntTypeFlags.BreakKeyValuePair)))
         : DelegateFactory.GenerateConstructorExpression(baseType);
     return ToType(newExpr, baseType);
 }
开发者ID:gentledepp,项目名称:AutoMapper,代码行数:7,代码来源:CollectionMapper.cs

示例4: Close

 // this has been through red and green phase, it has yet to see it's refactor phase
 public Type Close(Type conversionPatternType, Type sourceType, Type targetType)
 {
     var @interface = conversionPatternType.GetInterface(typeof (IConversionPattern<,>));
     if (@interface == null)
     {
         throw new ArgumentException(string.Format("Type {0} doesn't implement {1} and therefore is invalid for this operation.", conversionPatternType, typeof (IConversionPattern<,>)));
     }
     var arguments = @interface.GetGenericArguments();
     var interfaceSourceType = arguments[0];
     var interfaceTargetType = arguments[1];
     if (conversionPatternType.IsGenericType == false)
     {
         if (sourceType.Is(interfaceSourceType) && targetType.Is(interfaceTargetType))
         {
             return conversionPatternType;
         }
         return null;
     }
     var openClassArguments = conversionPatternType.GetGenericArguments();
     var parameters = new Type[openClassArguments.Length];
     if (TryAddParameters(sourceType, interfaceSourceType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (TryAddParameters(targetType, interfaceTargetType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (parameters.Any(p => p == null))
     {
         return null;
     }
     return conversionPatternType.MakeGenericType(parameters);
 }
开发者ID:kkozmic,项目名称:Cartographer,代码行数:35,代码来源:ConversionPatternGenericCloser.cs

示例5: GetNonProxiedType

        /// <summary>
        /// Do a best guess on getting a non dynamic <see cref="Type"/>.
        /// </summary>
        /// <remarks>
        /// This is necessary for libraries like nhibernate that use proxied types.
        /// </remarks>
        public static Type GetNonProxiedType(Type type)
        {
            if (type.IsGenericType && !type.IsGenericTypeDefinition)
            {
                var genericArguments = new List<Type>();
                foreach (var genericArgument in type.GetGenericArguments())
                {
                    genericArguments.Add(GetNonProxiedType(genericArgument));
                }
                type = GetNonProxiedType(type.GetGenericTypeDefinition());
                return type.MakeGenericType(genericArguments.ToArray());
            }

            if (IsDynamic(type))
            {
                var baseType = type.BaseType;
                if (baseType == typeof(object))
                {
                    var interfaces = type.GetInterfaces();
                    if (interfaces.Length > 1)
                    {
                        return GetNonProxiedType(interfaces[0]);
                    }
                    throw new Exception(string.Format("Could not create non dynamic type for '{0}'.", type.FullName));
                }
                return GetNonProxiedType(baseType);
            }
            return type;
        }
开发者ID:peterjoh,项目名称:NHaml,代码行数:35,代码来源:ProxyExtracter.cs

示例6: GetHandler

        private static dynamic GetHandler(object message, Type type)
        {
            Type handlerType = type.MakeGenericType(message.GetType());

            dynamic handler = TinyIoCContainer.Current.Resolve(handlerType);
            return handler;
        }
开发者ID:jenspettersson,项目名称:Argentum,代码行数:7,代码来源:MessageProcessor.cs

示例7: AdaptFactories

        private static IEnumerable<IComponentRegistration> AdaptFactories(Type from, Type to,
            IServiceWithType requestedService, Func<AutofacService, IEnumerable<IComponentRegistration>> registrationAccessor)
        {
            Guard.NotNull("from", from);
            Guard.NotNull("to", to);
            Guard.NotNull("requestedService", requestedService);
            Guard.NotNull("registrationAccessor", registrationAccessor);

            var factoryService = new OpenGenericLooselyNamedService(String.Empty, from);

            return registrationAccessor(factoryService)
                .Select(r => 
                    {
                        var targetService = r.Services.OfType<OpenGenericLooselyNamedService>().First(s => factoryService.Equals(s));
                        return new ComponentRegistration(
                            Guid.NewGuid(),
                            new DelegateActivator(
                                requestedService.ServiceType,
                                (c, p) => Activator.CreateInstance(
                                    // Since we looked up factory interfaces only (from argument) - generic argument of s.ServiceType will be the type of configuration
                                    to.MakeGenericType(targetService.ServiceType.GetGenericArguments()[0]),
                                    c.ResolveComponent(r, Enumerable.Empty<Parameter>()), GetDisplayName(r.Metadata, targetService.Name))
                            ),
                            new CurrentScopeLifetime(),
                            InstanceSharing.None,
                            InstanceOwnership.ExternallyOwned,
                            new AutofacService[] { new LooselyNamedService(targetService.Name, requestedService.ServiceType) },
                            new Dictionary<string, object>());
                    });
        }
开发者ID:kingkino,项目名称:azure-documentdb-datamigrationtool,代码行数:30,代码来源:DataAdapterFactoryAdaptersRegistrationSource.cs

示例8: IsGenericAssignableFrom

 public static bool IsGenericAssignableFrom(Type t, Type other)
 {
     if (other.GetGenericArguments().Length != t.GetGenericArguments().Length)
         return false;
     var genericT = t.MakeGenericType(other.GetGenericArguments());
     return genericT.IsAssignableFrom(other);
 }
开发者ID:osdezwart,项目名称:SolrNet,代码行数:7,代码来源:TypeHelper.cs

示例9: GetServerCollectionHandlerHelper

        protected IServerCollectionHandler GetServerCollectionHandlerHelper(
            Type collectionHandlerType,
            ImplementationType aType,
            ImplementationType bType,
            RelationEndRole endRole)
        {
            if (Object.ReferenceEquals(aType, null)) { throw new ArgumentNullException("aType"); }
            if (Object.ReferenceEquals(bType, null)) { throw new ArgumentNullException("bType"); }
            try
            {
                // dynamically translate generic types into provider-known types
                Type[] genericArgs;
                if (endRole == RelationEndRole.A)
                {
                    genericArgs = new Type[] { aType.Type, bType.Type, aType.Type, bType.Type };
                }
                else
                {
                    genericArgs = new Type[] { aType.Type, bType.Type, bType.Type, aType.Type };
                }

                Type resultType = collectionHandlerType.MakeGenericType(genericArgs);
                return (IServerCollectionHandler)Activator.CreateInstance(resultType);
            }
            catch (Exception ex)
            {
                var msg = String.Format(
                    "Failed to create IServerCollectionHandler for A=[{0}], B=[{1}], role=[{2}]",
                    aType,
                    bType,
                    endRole);
                Log.Error(msg, ex);
                throw;
            }
        }
开发者ID:daszat,项目名称:zetbox,代码行数:35,代码来源:ServerObjectHandlerFactory.cs

示例10: IsAssignableFromGenericTypeDefinition

        public static bool IsAssignableFromGenericTypeDefinition(this Type type, Type genericTypeDefinition)
        {
            var result = false;

            if (genericTypeDefinition.IsGenericTypeDefinition)
            {
                var typeParameters = genericTypeDefinition.GetGenericArguments();
                var typeArguments = type.GetGenericArguments();

                if (typeParameters.Length == typeArguments.Length)
                {
                    var genericParameterConstraintsAreSatisfied = typeParameters
                        .Zip(typeArguments, MatchesGenericParameterConstraints)
                        .All(x => x);

                    if (genericParameterConstraintsAreSatisfied)
                    {
                        var otherType = genericTypeDefinition.MakeGenericType(typeArguments);

                        result = type.IsAssignableFrom(otherType);
                    }
                }
            }

            return result;
        }
开发者ID:chrisblock,项目名称:Fuzzing,代码行数:26,代码来源:TypeExtensions.cs

示例11: CreateMagicModel

 private static object CreateMagicModel(Type genericType, IPublishedContent content)
 {
     var contentType = content.GetType();
     var modelType = genericType.MakeGenericType(contentType);
     var model = Activator.CreateInstance(modelType, content);
     return model;
 }
开发者ID:ksolberg,项目名称:Hybrid-Framework-for-Umbraco-v7-Best-Practises,代码行数:7,代码来源:ModelLogic.cs

示例12: TriggerEntityChangeEvent

 private void TriggerEntityChangeEvent(Type genericEventType, object entity)
 {
     var entityType = entity.GetType();
     var eventType = genericEventType.MakeGenericType(entityType);
     //:todo 成功之后才触发~
     EventsManager.Trigger(eventType, null, (IEventData)Activator.CreateInstance(eventType, entity));
 }
开发者ID:shoy160,项目名称:Shoy.Common,代码行数:7,代码来源:EntityChangedEventHelper.cs

示例13: Writer

        public Writer(Type writerType, Type resourceType = null)
        {
            if (writerType == null)
            {
                throw new ArgumentNullException("writerType");
            }

            if (writerType.IsOpenGeneric())
            {
                if (resourceType == null)
                {
                    throw new ArgumentNullException("resourceType", "resourceType is required if the writerType is an open generic");
                }

                _resourceType = resourceType;
                _writerType = writerType.MakeGenericType(resourceType);
            }
            else
            {
                var @interface = writerType.FindInterfaceThatCloses(typeof (IMediaWriter<>));
                if (@interface == null)
                {
                    throw new ArgumentOutOfRangeException("writerType", "writerType must be assignable to IMediaWriter<>");
                }

                _writerType = writerType;
                _resourceType = @interface.GetGenericArguments().First();
            }
        }
开发者ID:roend83,项目名称:fubumvc,代码行数:29,代码来源:Writer.cs

示例14: GenericModelBinderProvider

        public GenericModelBinderProvider(Type modelType, Type modelBinderType)
        {
            // The binder can be a closed type, in which case it will be instantiated directly. If the binder
            // is an open type, the type arguments will be determined at runtime and the corresponding closed
            // type instantiated.

            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }
            if (modelBinderType == null)
            {
                throw new ArgumentNullException("modelBinderType");
            }

            ValidateParameters(modelType, modelBinderType);
            bool modelBinderTypeIsOpenGeneric = modelBinderType.IsGenericTypeDefinition;

            _modelType = modelType;
            _modelBinderFactory = typeArguments =>
            {
                Type closedModelBinderType = (modelBinderTypeIsOpenGeneric) ? modelBinderType.MakeGenericType(typeArguments) : modelBinderType;
                return (IExtensibleModelBinder)Activator.CreateInstance(closedModelBinderType);
            };
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:25,代码来源:GenericModelBinderProvider.cs

示例15: CreateType

 public static Type CreateType(Type type, params Type[] genericArguments)
 {
     if(genericArguments == null) throw new System.ArgumentNullException("genericArguments");
     if(type == null) throw new System.ArgumentNullException("type");
     var result = type.MakeGenericType(genericArguments);
     return result;
 }
开发者ID:barbarossia,项目名称:ConsoleApplication2,代码行数:7,代码来源:Utilities.cs


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