MakeGenericType() public method

Substitutes the elements of an array of types for the type parameters of the current generic type definition and returns a T:System.Type object representing the resulting constructed type.
The current type does not represent a generic type definition. That is, returns false. is null.-or- Any element of is null. The number of elements in is not the same as the number of type parameters in the current generic type definition.-or- Any element of does not satisfy the constraints specified for the corresponding type parameter of the current generic type. -or- contains an element that is a pointer type ( returns true), a by-ref type ( returns true), or . The invoked method is not supported in the base class. Derived classes must provide an implementation.
public MakeGenericType ( ) : Type
return Type
 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);
 }
 internal static System.Type GetType(string rootType, System.Type[] typeArgs, string type, int index, ParameterElementCollection parameters)
 {
     if (string.IsNullOrEmpty(type))
     {
         if ((typeArgs != null) && (index < typeArgs.Length))
         {
             return(typeArgs[index]);
         }
         int num = (typeArgs == null) ? 0 : typeArgs.Length;
         if (num == 0)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.Runtime.Serialization.SR.GetString("KnownTypeConfigIndexOutOfBoundsZero", new object[] { rootType, num, index }));
         }
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.Runtime.Serialization.SR.GetString("KnownTypeConfigIndexOutOfBounds", new object[] { rootType, num, index }));
     }
     System.Type type2 = System.Type.GetType(type, true);
     if (!type2.IsGenericTypeDefinition)
     {
         return(type2);
     }
     if (parameters.Count != type2.GetGenericArguments().Length)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.Runtime.Serialization.SR.GetString("KnownTypeConfigGenericParamMismatch", new object[] { type, type2.GetGenericArguments().Length, parameters.Count }));
     }
     System.Type[] typeArguments = new System.Type[parameters.Count];
     for (int i = 0; i < typeArguments.Length; i++)
     {
         typeArguments[i] = parameters[i].GetType(rootType, typeArgs);
     }
     return(type2.MakeGenericType(typeArguments));
 }
Beispiel #3
0
        protected virtual IPropertyChangeEvent NewPropertyChangeEvent(IProperty property, object oldValue, object newValue)
        {
            sType realType = _defaultPropertyChangeEventType
                             .MakeGenericType(property.Config.GetType().GetGenericArguments());

            return((IPropertyChangeEvent)Activator.CreateInstance(realType, property, oldValue, newValue));
        }
        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>());
                    });
        }
        private static dynamic GetHandler(object message, Type type)
        {
            Type handlerType = type.MakeGenericType(message.GetType());

            dynamic handler = TinyIoCContainer.Current.Resolve(handlerType);
            return handler;
        }
 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));
 }
        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;
            }
        }
Beispiel #8
0
        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;
        }
 // 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);
 }
        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);
            }
        }
 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;
 }
Beispiel #12
0
        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>());
            }
        }
        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);
            };
        }
Beispiel #14
0
        private static BaseInvokableCall GetObjectCall(UnityEngine.Object target, MethodInfo method, ArgumentCache arguments)
        {
            System.Type type = typeof(UnityEngine.Object);
            if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName))
            {
                System.Type type1 = System.Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, false);
                if (type1 != null)
                {
                    type = type1;
                }
                else
                {
                    type = typeof(UnityEngine.Object);
                }
            }
            System.Type     type2         = typeof(CachedInvokableCall <>);
            System.Type[]   typeArguments = new System.Type[] { type };
            System.Type[]   types         = new System.Type[] { typeof(UnityEngine.Object), typeof(MethodInfo), type };
            ConstructorInfo constructor   = type2.MakeGenericType(typeArguments).GetConstructor(types);

            UnityEngine.Object unityObjectArgument = arguments.unityObjectArgument;
            if ((unityObjectArgument != null) && !type.IsAssignableFrom(unityObjectArgument.GetType()))
            {
                unityObjectArgument = null;
            }
            object[] parameters = new object[] { target, method, unityObjectArgument };
            return(constructor.Invoke(parameters) as BaseInvokableCall);
        }
Beispiel #15
0
        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();
            }
        }
Beispiel #16
0
        /// <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;
        }
Beispiel #17
0
        public IList List(Type type, Command cmd, Region region)
        {
            TimeWatch.________________________________________________________("Peanut->Execute SQL Return List");
            if (region == null)
            {
                region = new Region {
                    Start = 0, Size = 99999999
                }
            }
            ;
            IList items = null;

            if (Mappings.ObjectMapper.CurrentOM.SelectChange != null)
            {
                Mappings.ObjectMapper.CurrentOM.SelectChange.Change(cmd);
            }
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(type);
            if (region.Size > DBContext.DefaultListMaxSize)
            {
                items = (IList)Activator.CreateInstance(itemstype, DBContext.DefaultListMaxSize);
            }
            else
            {
                items = (IList)Activator.CreateInstance(itemstype, region.Size);
            }
            object item = null;

            using (IDataReader reader = ExecuteReader(cmd))
            {
                int index = 0;
                while (reader.Read())
                {
                    if (index >= region.Start)
                    {
                        item = Activator.CreateInstance(type);

                        if (item is IEntityState)
                        {
                            ((IEntityState)item).ConnectionType = this.Type;
                            ((IEntityState)item).LoadData(reader);
                        }
                        else
                        {
                            Mappings.ObjectMapper.CurrentSelectReader.ReaderToObject(reader, item);
                        }
                        items.Add(item);
                        if (items.Count == region.Size)
                        {
                            cmd.DbCommand.Cancel();
                            reader.Close();
                            break;
                        }
                    }
                    index++;
                }
            }
            TimeWatch.________________________________________________________();
            return(items);
        }
 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;
 }
Beispiel #19
0
 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);
 }
Beispiel #20
0
            public object BuildForOpenType(Type openType)
            {
                Type delegateType = openType.MakeGenericType(ParameterTypes);

                LambdaExpression newExp = Expression.Lambda(delegateType, MethodCall, Parameters);

                return newExp.Compile();
            }
		private static Type GetGenericTypeSafely(Type source, params Type[] args)
		{
			if (!source.IsGenericTypeDefinition)
				throw new ArgumentException("source must be a generic type definition", "source");
			if (source.GetGenericArguments().Length != args.Length)
				throw new ArgumentException("incorrect number of arguments", "args");
			return source.MakeGenericType(args);
		}
Beispiel #22
0
        private static ITypeAmendment CreateGenericAmendment(Type amendmentType, Type targetType)
        {
            var entityAmendmentCtor = amendmentType.MakeGenericType(targetType).GetConstructor(Type.EmptyTypes);
            if (entityAmendmentCtor == null)
                throw new Exception("Cannot create '" + amendmentType.Name + "' for '" + targetType.Name + "'.");

            return (ITypeAmendment)entityAmendmentCtor.Invoke(new object[0]);
        }
 public KnownGenericTypesAttribute(Type genericTypeDefinition, string genericArgumentWildcard, Type context)
 {
     if (genericTypeDefinition == null) throw new ArgumentNullException(nameof(genericTypeDefinition));
     if (!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Invalid argument. Expected a generic type definition.");
     if (genericArgumentWildcard == null) throw new ArgumentNullException(nameof(genericArgumentWildcard));
     if (context == null) throw new ArgumentNullException(nameof(context));
     base.KnownTypes = MatchTypes(genericArgumentWildcard, context.Assembly).Select(t => genericTypeDefinition.MakeGenericType(t)).ToArray();
 }
Beispiel #24
0
        /// <summary>
        /// Generates a new method call operation.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <param name="context"></param>
        /// <param name="expression"></param>
        /// <param name="genericArgIndexes"></param>
        /// <returns></returns>
        public static IOperation CreateMethodCallOperation(Type type, OperationContext context, MethodCallExpression expression, params int[] genericArgIndexes)
        {
            Contract.Requires<ArgumentNullException>(type != null);
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(expression != null);
            Contract.Requires<ArgumentNullException>(genericArgIndexes != null);

            return (IOperation)Activator.CreateInstance(type.MakeGenericType(genericArgIndexes.Select(i => expression.Method.GetGenericArguments()[i]).ToArray()), context, expression);
        }
Beispiel #25
0
 /// <summary>
 /// Creates the type of the generic.
 /// </summary>
 /// <param name="type">The generic type to create e.g. List&lt;&gt;</param>
 /// <param name="arguments">The list of subtypes for the generic type, e.g string in List&lt;string&gt;</param>
 /// <param name="parameters">List of parameters to pass to the constructor.</param>
 /// <returns></returns>
 public static object CreateGenericType(Type type, Type[] arguments, params  object[] parameters)
 {
     Type genericType = type.MakeGenericType(arguments);
     object obj;
     if (parameters != null && parameters.Any())
         obj = Activator.CreateInstance(genericType, parameters);
     else
         obj = Activator.CreateInstance(genericType);
     return obj;
 }
Beispiel #26
0
        //
        // Generic type instantiation helpers
        //
        // How to: Examine and Instantiate Generic Types with Reflection
        // see http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
        public static object CreateInstanceOfGenericType(Type genericTypeDefinition, Type[] parms)
        {
            // construct type from definition
            Type constructedType = genericTypeDefinition.MakeGenericType(parms);

            // create instance of constructed type
            object obj = Activator.CreateInstance(constructedType);

            return obj;
        }
Beispiel #27
0
 static TypeResolver CreateResolverObject(Type orType, Categories cat, Type genericType, params Type[] genericArgs)
 {
     var type = genericType.MakeGenericType(genericArgs);
     var ctor = type.GetConstructor(Type.EmptyTypes);
     var obj = ctor.Invoke(emptyObjects);
     var res=(TypeResolver)obj;
     res.Category = cat;
     res.Type = orType;
     return res;
 }
Beispiel #28
0
        public static void Publish(this UpdatedEventInfo updatedEventInfo, ISession session, Type eventType,
            Func<UpdatedEventInfo, ISession, Type, object> getArgs)
        {
            Type type = updatedEventInfo.GetType().GenericTypeArguments[0];

            List<Type> types = GetEntityTypes(type).Reverse().ToList();

            types.ForEach(
                t => EventContext.Instance.Publish(eventType.MakeGenericType(t), getArgs(updatedEventInfo, session, t)));
        }
Beispiel #29
0
        public void addAgent(Type policyType, Type actionValueType, params object[] actionValueParameters)
        {
            policyType = policyType.MakeGenericType(typeof(int[]), typeof(int[]));
            Policy<int[], int[]> newPolicy = (Policy<int[],int[]>)Activator.CreateInstance(policyType);

            actionValueType = actionValueType.MakeGenericType(typeof(int[]), typeof(int[]));
            ActionValue<int[], int[]> newActionValue = (ActionValue<int[], int[]>)Activator.CreateInstance(actionValueType, new IntArrayComparer(), new IntArrayComparer(), availableActions, startState, actionValueParameters);

            agent = new Agent<int[], int[]>(startState, newPolicy, newActionValue, availableActions);
        }
 public static bool Implements(this Type classType, Type interfaceType)
 {
     var genericArguments = classType.GetGenericArguments();
     if (genericArguments.Any()) {
         return classType.GetInterface(interfaceType.MakeGenericType(genericArguments).Name) != null;
     }
     else {
         return classType.GetInterface(interfaceType.Name) != null;
     }
 }
        /// <summary>
        /// Invokes a method on type.
        /// </summary>
        /// <param name="script"></param>
        /// <param name="scope"></param>
        /// <param name="obj">The object that the method before returned, this can be null for static methods.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="methodName">The method we want to call, if null, we are assuming that we want to call the constructor for this type.</param>
        /// <param name="arguments">The arguments for the method.</param>
        /// <param name="generics">If generic, the types we are passing to it.</param>
        /// <param name="locals">Local variables.</param>
        /// <returns>The result of the method, or Slimterpreter.Void if no return type.</returns>
        protected object Invoke(Script script, Scope scope, object obj, Type objectType, string methodName, List<List<Token>> arguments, List<string> generics)
        {
            if (generics.Count != 0)
            {
                var genericTypes = new Type[generics.Count];
                for (int i = 0; i < generics.Count; i++)
                {
                    Type type = script.FindType(generics[i]);
                    if (type == null)
                    {
                        throw new InvalidCastException("Cannot cast to type " + generics[i]);
                    }
                    genericTypes[i] = type;
                }
                objectType = objectType.MakeGenericType(genericTypes);
            }

            // Solve the parameters.
            var argumentTypes = new Type[arguments.Count];
            var argumentValues = new object[arguments.Count];
            for (int i = 0; i < arguments.Count; i++)
            {
                object res = null;
                // We need to get to the end of the list of Calls...
                for (int j = 0; j < arguments[i].Count; j++)
                {
                    if (j + 1 < arguments[i].Count)
                    {
                        res = arguments[i][j].Execute(script, null, null, res);
                    }
                    else if (j + 1 == arguments[i].Count)
                    {
                        argumentValues[i] = arguments[i][j].Execute(script, scope, null, res);
                        if (argumentValues[i] == null)
                        {
                            argumentTypes[i] = typeof (object);
                        }
                        else
                        {
                            argumentTypes[i] = argumentValues[i].GetType();
                        }
                    }
                }
            }

            if (methodName == null)
            {
                return ConstructorInvoke(objectType, argumentTypes, argumentValues);
            }
            else
            {
                return MethodInvoke(obj, methodName, objectType, argumentTypes, argumentValues);
            }
        }
Beispiel #32
0
    public static Type MakeGenericType(Type type, params Type[] typeArguments)
    {
      Contract.Requires(type != null);
      Contract.Requires(typeArguments != null);
      Contract.Ensures(Contract.Result<Type>() != null);

      Contract.Assume(type.IsGenericTypeDefinition);
      Contract.Assume(typeArguments.Length == type.GetGenericArguments().Length);

      return type.MakeGenericType(typeArguments);
    }
Beispiel #33
0
 /// <summary>
 /// Gets a specific validator
 /// </summary>
 /// <param name="ObjectType">Object type</param>
 /// <returns>The specified validator</returns>
 public static IValidator GetValidator(Type ObjectType)
 {
     if (!Validators.ContainsKey(ObjectType))
     {
         System.Type ValidatorType = typeof(Validator <>);
         ValidatorType = ValidatorType.MakeGenericType(ObjectType);
         IValidator Validator = (IValidator)Activator.CreateInstance(ValidatorType);
         Validators.Add(ObjectType, Validator);
     }
     return(Validators[ObjectType]);
 }
            protected override System.Type MakeGeneric(GenericTypeSlim type, System.Type typeDefinition, ReadOnlyCollection <System.Type> arguments)
            {
                var res = default(System.Type);

                if (typeDefinition != null && arguments.All(a => a != null))
                {
                    res = typeDefinition.MakeGenericType(arguments.ToArray());
                }

                return(res);
            }
Beispiel #35
0
 // RegisterClassCodecs
 private static void RegisterClassCodecs(System.Type genericType)
 {
     foreach (var type in GetAllTypesImplementingGenericType(genericType))
     {
         if (!type.IsGenericType)
         {
             var baseClassType = genericType.MakeGenericType(type);
             System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(baseClassType.TypeHandle);
         }
     }
 }
Beispiel #36
0
 private static Type tryMakeCombinerType(Type genericCombinerType, Type targetType)
 {
     try
     {
         return genericCombinerType.MakeGenericType(targetType);
     }
     catch (InvalidOperationException)
     {
         return null;
     }
 }
        public static bool MatchGenerics(Type generalType, List<Type> possibleParameters, Type targetType)
        {
            foreach (var type in possibleParameters)
            {
                Type fullType = generalType.MakeGenericType(type);
                if (fullType.Equals(targetType))
                    return true;
            }

            return false;
        }
Beispiel #38
0
    void Start()
    {
        // TODO 蓝大, 主工程的测试代码
        System.Type t = typeof(Ron2 <>);
        UnityEngine.Debug.Log("t Type ==> " + t);
        System.Type constructed = t.MakeGenericType(new System.Type[] { typeof(string) });
        object      obj         = System.Activator.CreateInstance(constructed, new object[] { "Test Success" });


        StartCoroutine(LoadHotFixAssembly());
    }
 public static void CallGenericStaticConstructor(System.Type constructorClassType, System.Type genericType)
 {
     if (constructorClassType.IsClass && constructorClassType.IsAbstract && constructorClassType.IsSealed)
     {
         var genericClass = constructorClassType.MakeGenericType(genericType);
         RuntimeHelpers.RunClassConstructor(genericClass.TypeHandle);
     }
     else
     {
         throw new Exception($"이 클래스는 Generic Static Class가 아닙니다!: {constructorClassType.ToString()}");
     }
 }
Beispiel #40
0
        internal IList List(Type type, IConnectinContext cc, Region region)
        {
            TimeWatch.________________________________________________________("Peanut->SQL to list");
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(type);
            IList result;

            if (region == null)
            {
                region = new Region(0, 99999999);
            }
            if (region.Size > DBContext.DefaultListMaxSize)
            {
                result = (IList)Activator.CreateInstance(itemstype, DBContext.DefaultListMaxSize);
            }
            else
            {
                result = (IList)Activator.CreateInstance(itemstype, region.Size);
            }
            Mappings.CommandReader cr = Mappings.CommandReader.GetReader(mBaseSql, type);
            int     index             = 0;
            Command cmd = GetCommand();

            TimeWatch.________________________________________________________("Peanut->DataReader to list");
            using (IDataReader reader = cc.ExecuteReader(cmd))
            {
                TimeWatch.________________________________________________________("Peanut->Read Data");
                while (reader.Read())
                {
                    if (index >= region.Start)
                    {
                        object item = Activator.CreateInstance(type);
                        cr.ReaderToObject(reader, item);
                        result.Add(item);
                        if (result.Count >= region.Size)
                        {
                            cmd.DbCommand.Cancel();
                            reader.Dispose();
                            break;
                        }
                    }
                    index++;
                }
                TimeWatch.________________________________________________________();
            }
            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________();
            return(result);
        }
Beispiel #41
0
        public static System.Type MakeGenericType(System.Type genericTypeDefinition, Type[] typeParameters)
        {
            try
            {
                if (genericTypeDefinition is TypeBuilder typeBuilder)
                {
                    // For TypeBuilder.GetConstructor(), TypeBuilder.GetMethod() and TypeBuilder.GetField() to work,
                    // the typebuilder needs to keep track of generic types that it produces.  To do this, the typeBuilder
                    // MakeGeneric method needs to be used over just the normal Type.MakeGenericType() method.
                    //for (int i = 0; i < typeParameters.Length; i++)
                    //{
                    // Console.WriteLine($"MakeGenericType TP[{i}]: {typeParameters[i].Name}");
                    //}

                    return(typeBuilder.MakeGenericType(typeParameters));
                }

                //for (int i = 0; i < typeParameters.Length; i++)
                //{
                // var parameter = typeParameters[i];

                // if (parameter.DeclaringType != null && ReferenceEquals(genericTypeDefinition, parameter.DeclaringType))
                // {
                //  throw new Exception("Declaring type of parameter is same as generic type definition.");
                // }
                //}

                var result = genericTypeDefinition.MakeGenericType(typeParameters);

                //if (result.IsGenericTypeDefinition)
                //{
                // throw new Exception("MakeGenericType returned a generic type definition and not a generic instance.");
                //}
                return(result);
            }
            catch
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("Could not make a genric type with the following types:");
                builder.AppendLine($"Defininition: {genericTypeDefinition.AssemblyQualifiedName}");
                for (int i = 0; i < typeParameters.Length; i++)
                {
                    builder.AppendLine($"{i}: {typeParameters[i].AssemblyQualifiedName}");
                }


                throw new Exception(builder.ToString());
            }
        }
Beispiel #42
0
 public static System.Type GetType(string typeStr)
 {
     System.Type type = null;
     if (s_typeCache.TryGetValue(typeStr, out type))
     {
         return(type);
     }
     if ((typeStr.Contains("`") && typeStr.Contains("[")) && typeStr.Contains("]"))
     {
         string        str           = typeStr.Substring(0, typeStr.IndexOf("["));
         int           index         = typeStr.IndexOf("[");
         int           num2          = typeStr.LastIndexOf("]");
         char[]        separator     = new char[] { ',' };
         string[]      strArray      = typeStr.Substring(index + 1, (num2 - index) - 1).Split(separator);
         System.Type   type2         = GetType(str);
         System.Type[] typeArguments = new System.Type[strArray.Length];
         for (int i = 0; i < strArray.Length; i++)
         {
             typeArguments[i] = GetType(strArray[i]);
         }
         System.Type type3 = type2.MakeGenericType(typeArguments);
         s_typeCache.Add(typeStr, type3);
         return(type3);
     }
     System.Type type4 = Utility.GetType(typeStr);
     if (type4 == null)
     {
         Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
         for (int j = 0; j < assemblies.Length; j++)
         {
             if (assemblies[j] != null)
             {
                 System.Type[] types = assemblies[j].GetTypes();
                 for (int k = 0; k < types.Length; k++)
                 {
                     if (typeStr == types[k].Name)
                     {
                         type4 = types[k];
                         s_typeCache.Add(typeStr, type4);
                         return(type4);
                     }
                 }
             }
         }
     }
     s_typeCache.Add(typeStr, type4);
     return(type4);
 }
Beispiel #43
0
 private static void InitializeValidator(Attribute attribute, System.Type validatorClass, IValidator entityValidator)
 {
     /* This method was added to supply major difference between JAVA and NET generics.
      * So far in JAVA the generic type is something optional, in NET mean "strongly typed".
      * In this case we don't know exactly wich is the generic version of "IInitializableValidator<>"
      * so we create the type on the fly and invoke the Initialize method by reflection.
      * All this work is only to give to the user the ability of implement IInitializableValidator<>
      * without need to inherit from a base class or implement a generic and a no generic version of
      * the method Initialize.
      */
     System.Type[] args        = { attribute.GetType() };
     System.Type   concreteIvc = BaseInitializableType.MakeGenericType(args);
     if (concreteIvc.IsAssignableFrom(validatorClass))
     {
         MethodInfo initMethod = concreteIvc.GetMethod("Initialize");
         initMethod.Invoke(entityValidator, new object[] { attribute });
     }
 }
Beispiel #44
0
        static StackObject *MakeGenericType_12(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Type[] @typeArguments = (System.Type[]) typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.MakeGenericType(@typeArguments);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Beispiel #45
0
        public IList ListProc(Type entity, object parameter)
        {
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(entity);
            IList result = (IList)Activator.CreateInstance(itemstype);

            Mappings.ProcDataReader dr = Mappings.ProcDataReader.GetDataReader(parameter.GetType(), entity);
            using (IDataReader reader = mHandler.ExecProcReader(parameter))
            {
                while (reader.Read())
                {
                    object item = Activator.CreateInstance(entity);
                    dr.ReaderToObject(reader, item);
                    result.Add(item);
                }
            }

            return(result);
        }
Beispiel #46
0
        internal static MethodInfo GetDeepCloneForList(System.Type elementType)
        {
            MethodInfo info = null;

            foreach (MethodInfo info2 in from m in typeof(CloneHelper).GetMethods()
                     where m.Name.Equals("DeepClone") && (m.GetGenericArguments().Length == 1)
                     select m)
            {
                MethodInfo    info3         = info2.MakeGenericMethod(new System.Type[] { elementType });
                ParameterInfo info4         = info3.GetParameters()[0];
                System.Type   type          = typeof(List <>);
                System.Type[] typeArguments = new System.Type[] { elementType };
                System.Type   c             = type.MakeGenericType(typeArguments);
                if (info4.ParameterType.IsAssignableFrom(c))
                {
                    info = info3;
                }
            }
            return(info);
        }
Beispiel #47
0
        public object Parse(System.Collections.Specialized.NameValueCollection data, string key, string prefix, out bool succeed)
        {
            IList <T> items = null;

            succeed = true;
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(typeof(T));
            items     = (IList <T>)Activator.CreateInstance(itemstype);
            int count = 0;

            string[] values;
            Dictionary <System.Reflection.PropertyInfo, string[]> valueCollection = new Dictionary <System.Reflection.PropertyInfo, string[]>();

            foreach (System.Reflection.PropertyInfo pi in Properties)
            {
                values = ConverCore.GetValues(data, pi.Name, prefix);
                if (values != null && values.Length > count)
                {
                    count = values.Length;
                }
                valueCollection.Add(pi, values);
            }

            for (int i = 0; i < count; i++)
            {
                System.Collections.Specialized.NameValueCollection itemdata = new System.Collections.Specialized.NameValueCollection();
                foreach (System.Reflection.PropertyInfo pi in Properties)
                {
                    values = valueCollection[pi];
                    if (values != null && i < values.Length)
                    {
                        itemdata.Add(pi.Name, values[i]);
                    }
                }
                T item = BinderAdapter.CreateInstance <T>(itemdata);
                items.Add(item);
            }
            return(items);
        }
Beispiel #48
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jsonObject = JObject.Load(reader);
            JToken  property   = jsonObject[this.PropertyName];

            Type propertyType = this.decoratorTypeRetriever.GetTypeForToken(property);

            if (propertyType == null)
            {
                propertyType = this.DefaultType;
                return(jsonObject.ToObject(propertyType, serializer));
            }
            // create generic payload based on resource (like if resource is customer, then object type
            // will be like ResourceCreatedPayload<Customer> or MessageSubscriptionPayload<Customer>
            if (jsonObject["resource"]?["typeId"] is JToken typeIdToken)
            {
                var resourceType       = this.typeRetriever.GetTypeForToken(typeIdToken);
                var genericPayloadType = propertyType.MakeGenericType(resourceType);
                return(jsonObject.ToObject(genericPayloadType, serializer));
            }
            throw new JsonSerializationException($"Unknown subscription payload type: {jsonObject.ToString(Formatting.None)}");
        }
Beispiel #49
0
 private static System.Collections.IList GetEntities <TData>(System.Collections.IEnumerable datas, System.Type type, Func <TData, string, object> func) where TData : class
 {
     System.Collections.IList result;
     if (datas == null)
     {
         result = null;
     }
     else
     {
         System.Type typeFromHandle = typeof(System.Collections.Generic.List <>);
         System.Type type2          = typeFromHandle.MakeGenericType(new System.Type[]
         {
             type
         });
         System.Collections.IList list = System.Activator.CreateInstance(type2) as System.Collections.IList;
         foreach (object current in datas)
         {
             list.Add(EntityFactory.GetEntity <TData>(current as TData, type, func));
         }
         result = list;
     }
     return(result);
 }
        static StackObject *MakeGenericType_4(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Type[] @typeArguments = (System.Type[]) typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.MakeGenericType(@typeArguments);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Beispiel #51
0
        /// <summary>
        /// The CreateType method creates a new data class with a given set of public properties and returns the System.Type object for the newly created class. If a data class with an identical sequence of properties has already been created, the System.Type object for this class is returned.
        /// Data classes implement private instance variables and read/write property accessors for the specified properties.Data classes also override the Equals and GetHashCode members to implement by-value equality.
        /// Data classes are created in an in-memory assembly in the current application domain. All data classes inherit from <see cref="DynamicClass"/> and are given automatically generated names that should be considered private (the names will be unique within the application domain but not across multiple invocations of the application). Note that once created, a data class stays in memory for the lifetime of the current application domain. There is currently no way to unload a dynamically created data class.
        /// The dynamic expression parser uses the CreateClass methods to generate classes from data object initializers. This feature in turn is often used with the dynamic Select method to create projections.
        /// </summary>
        /// <param name="properties">The DynamicProperties</param>
        /// <param name="createParameterCtor">Create a constructor with parameters. Default set to true. Note that for Linq-to-Database objects, this needs to be set to false.</param>
        /// <returns>Type</returns>
        /// <example>
        /// <code>
        /// <![CDATA[
        /// DynamicProperty[] props = new DynamicProperty[] { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
        /// Type type = DynamicClassFactory.CreateType(props);
        /// DynamicClass dynamicClass = Activator.CreateInstance(type) as DynamicClass;
        /// dynamicClass.SetDynamicProperty("Name", "Albert");
        /// dynamicClass.SetDynamicProperty("Birthday", new DateTime(1879, 3, 14));
        /// Console.WriteLine(dynamicClass);
        /// ]]>
        /// </code>
        /// </example>
        public static System.Type CreateType(IList <DynamicProperty> properties, bool createParameterCtor = true)
        {
            //Check.HasNoNulls(properties, nameof(properties));

            System.Type[] types = properties.Select(p => p.Type).ToArray();
            string[]      names = properties.Select(p => p.Name).ToArray();

            string key = GenerateKey(properties, createParameterCtor);

            System.Type type;
            if (!GeneratedTypes.TryGetValue(key, out type))
            {
                // We create only a single class at a time, through this lock
                // Note that this is a variant of the double-checked locking.
                // It is safe because we are using a thread safe class.
                lock (GeneratedTypes)
                {
                    if (!GeneratedTypes.TryGetValue(key, out type))
                    {
                        int index = Interlocked.Increment(ref _index);

                        string name = names.Length != 0 ? $"<>f__AnonymousType{index}`{names.Length}" : $"<>f__AnonymousType{index}";

                        TypeBuilder tb = ModuleBuilder.DefineType(name, TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit, typeof(object));
                        tb.SetCustomAttribute(CompilerGeneratedAttributeBuilder);

                        GenericTypeParameterBuilder[] generics;

                        if (names.Length != 0)
                        {
                            string[] genericNames = names.Select(genericName => $"<{genericName}>j__TPar").ToArray();
                            generics = tb.DefineGenericParameters(genericNames);
                            foreach (GenericTypeParameterBuilder b in generics)
                            {
                                b.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
                            }
                        }
                        else
                        {
                            generics = new GenericTypeParameterBuilder[0];
                        }

                        var fields = new FieldBuilder[names.Length];

                        // There are two for cycles because we want to have all the getter methods before all the other methods
                        for (int i = 0; i < names.Length; i++)
                        {
                            // field
                            fields[i] = tb.DefineField($"<{names[i]}>i__Field", generics[i].AsType(), FieldAttributes.Private | FieldAttributes.InitOnly);
                            fields[i].SetCustomAttribute(DebuggerBrowsableAttributeBuilder);

                            PropertyBuilder property = tb.DefineProperty(names[i], PropertyAttributes.None, CallingConventions.HasThis, generics[i].AsType(), EmptyTypes);

                            // getter
                            MethodBuilder getter = tb.DefineMethod($"get_{names[i]}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, generics[i].AsType(), null);
                            getter.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
                            ILGenerator ilgeneratorGetter = getter.GetILGenerator();
                            ilgeneratorGetter.Emit(OpCodes.Ldarg_0);
                            ilgeneratorGetter.Emit(OpCodes.Ldfld, fields[i]);
                            ilgeneratorGetter.Emit(OpCodes.Ret);
                            property.SetGetMethod(getter);

                            // setter
                            MethodBuilder setter = tb.DefineMethod($"set_{names[i]}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, null, new[] { generics[i].AsType() });
                            setter.SetCustomAttribute(CompilerGeneratedAttributeBuilder);

                            // workaround for https://github.com/dotnet/corefx/issues/7792
                            setter.DefineParameter(1, ParameterAttributes.In, generics[i].Name);

                            ILGenerator ilgeneratorSetter = setter.GetILGenerator();
                            ilgeneratorSetter.Emit(OpCodes.Ldarg_0);
                            ilgeneratorSetter.Emit(OpCodes.Ldarg_1);
                            ilgeneratorSetter.Emit(OpCodes.Stfld, fields[i]);
                            ilgeneratorSetter.Emit(OpCodes.Ret);
                            property.SetSetMethod(setter);
                        }

                        // ToString()
                        MethodBuilder toString = tb.DefineMethod("ToString", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(string), EmptyTypes);
                        toString.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
                        ILGenerator ilgeneratorToString = toString.GetILGenerator();
                        ilgeneratorToString.DeclareLocal(typeof(StringBuilder));
                        ilgeneratorToString.Emit(OpCodes.Newobj, StringBuilderCtor);
                        ilgeneratorToString.Emit(OpCodes.Stloc_0);

                        // Equals
                        MethodBuilder equals = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(bool), new[] { typeof(object) });
                        equals.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
                        equals.DefineParameter(1, ParameterAttributes.In, "value");

                        ILGenerator ilgeneratorEquals = equals.GetILGenerator();
                        ilgeneratorEquals.DeclareLocal(tb.AsType());
                        ilgeneratorEquals.Emit(OpCodes.Ldarg_1);
                        ilgeneratorEquals.Emit(OpCodes.Isinst, tb.AsType());
                        ilgeneratorEquals.Emit(OpCodes.Stloc_0);
                        ilgeneratorEquals.Emit(OpCodes.Ldloc_0);

                        Label equalsLabel = ilgeneratorEquals.DefineLabel();

                        // GetHashCode()
                        MethodBuilder getHashCode = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(int), EmptyTypes);
                        getHashCode.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
                        ILGenerator ilgeneratorGetHashCode = getHashCode.GetILGenerator();
                        ilgeneratorGetHashCode.DeclareLocal(typeof(int));

                        if (names.Length == 0)
                        {
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4_0);
                        }
                        else
                        {
                            // As done by Roslyn
                            // Note that initHash can vary, because string.GetHashCode() isn't "stable" for different compilation of the code
                            int initHash = 0;

                            for (int i = 0; i < names.Length; i++)
                            {
                                initHash = unchecked (initHash * (-1521134295) + fields[i].Name.GetHashCode());
                            }

                            // Note that the CSC seems to generate a different seed for every anonymous class
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, initHash);
                        }

                        for (int i = 0; i < names.Length; i++)
                        {
                            System.Type equalityComparerT = EqualityComparer.MakeGenericType(generics[i].AsType());

                            // Equals()
                            MethodInfo equalityComparerTDefault = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerDefault);
                            MethodInfo equalityComparerTEquals  = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerEquals);

                            // Illegal one-byte branch at position: 9. Requested branch was: 143.
                            // So replace OpCodes.Brfalse_S to OpCodes.Brfalse
                            ilgeneratorEquals.Emit(OpCodes.Brfalse, equalsLabel);
                            ilgeneratorEquals.Emit(OpCodes.Call, equalityComparerTDefault);
                            ilgeneratorEquals.Emit(OpCodes.Ldarg_0);
                            ilgeneratorEquals.Emit(OpCodes.Ldfld, fields[i]);
                            ilgeneratorEquals.Emit(OpCodes.Ldloc_0);
                            ilgeneratorEquals.Emit(OpCodes.Ldfld, fields[i]);
                            ilgeneratorEquals.Emit(OpCodes.Callvirt, equalityComparerTEquals);

                            // GetHashCode();
                            MethodInfo equalityComparerTGetHashCode = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerGetHashCode);
                            ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0);
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, -1521134295);
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0);
                            ilgeneratorGetHashCode.Emit(OpCodes.Mul);
                            ilgeneratorGetHashCode.Emit(OpCodes.Call, equalityComparerTDefault);
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldarg_0);
                            ilgeneratorGetHashCode.Emit(OpCodes.Ldfld, fields[i]);
                            ilgeneratorGetHashCode.Emit(OpCodes.Callvirt, equalityComparerTGetHashCode);
                            ilgeneratorGetHashCode.Emit(OpCodes.Add);

                            // ToString();
                            ilgeneratorToString.Emit(OpCodes.Ldloc_0);
                            ilgeneratorToString.Emit(OpCodes.Ldstr, i == 0 ? $"{{ {names[i]} = " : $", {names[i]} = ");
                            ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString);
                            ilgeneratorToString.Emit(OpCodes.Pop);
                            ilgeneratorToString.Emit(OpCodes.Ldloc_0);
                            ilgeneratorToString.Emit(OpCodes.Ldarg_0);
                            ilgeneratorToString.Emit(OpCodes.Ldfld, fields[i]);
                            ilgeneratorToString.Emit(OpCodes.Box, generics[i].AsType());

                            ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendObject);
                            ilgeneratorToString.Emit(OpCodes.Pop);
                        }

                        // Only create the default and with params constructor when there are any params.
                        // Otherwise default constructor is not needed because it matches the default
                        // one provided by the runtime when no constructor is present
                        if (createParameterCtor && names.Any())
                        {
                            // .ctor default
                            ConstructorBuilder constructorDef = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, EmptyTypes);
                            constructorDef.SetCustomAttribute(DebuggerHiddenAttributeBuilder);

                            ILGenerator ilgeneratorConstructorDef = constructorDef.GetILGenerator();
                            ilgeneratorConstructorDef.Emit(OpCodes.Ldarg_0);
                            ilgeneratorConstructorDef.Emit(OpCodes.Call, ObjectCtor);
                            ilgeneratorConstructorDef.Emit(OpCodes.Ret);

                            // .ctor with params
                            ConstructorBuilder constructor = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, generics.Select(p => p.AsType()).ToArray());
                            constructor.SetCustomAttribute(DebuggerHiddenAttributeBuilder);

                            ILGenerator ilgeneratorConstructor = constructor.GetILGenerator();
                            ilgeneratorConstructor.Emit(OpCodes.Ldarg_0);
                            ilgeneratorConstructor.Emit(OpCodes.Call, ObjectCtor);

                            for (int i = 0; i < names.Length; i++)
                            {
                                constructor.DefineParameter(i + 1, ParameterAttributes.None, names[i]);
                                ilgeneratorConstructor.Emit(OpCodes.Ldarg_0);

                                if (i == 0)
                                {
                                    ilgeneratorConstructor.Emit(OpCodes.Ldarg_1);
                                }
                                else if (i == 1)
                                {
                                    ilgeneratorConstructor.Emit(OpCodes.Ldarg_2);
                                }
                                else if (i == 2)
                                {
                                    ilgeneratorConstructor.Emit(OpCodes.Ldarg_3);
                                }
                                else if (i < 255)
                                {
                                    ilgeneratorConstructor.Emit(OpCodes.Ldarg_S, (byte)(i + 1));
                                }
                                else
                                {
                                    // Ldarg uses a ushort, but the Emit only accepts short, so we use a unchecked(...), cast to short and let the CLR interpret it as ushort.
                                    ilgeneratorConstructor.Emit(OpCodes.Ldarg, unchecked ((short)(i + 1)));
                                }

                                ilgeneratorConstructor.Emit(OpCodes.Stfld, fields[i]);
                            }

                            ilgeneratorConstructor.Emit(OpCodes.Ret);
                        }

                        // Equals()
                        if (names.Length == 0)
                        {
                            ilgeneratorEquals.Emit(OpCodes.Ldnull);
                            ilgeneratorEquals.Emit(OpCodes.Ceq);
                            ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0);
                            ilgeneratorEquals.Emit(OpCodes.Ceq);
                        }
                        else
                        {
                            ilgeneratorEquals.Emit(OpCodes.Ret);
                            ilgeneratorEquals.MarkLabel(equalsLabel);
                            ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0);
                        }

                        ilgeneratorEquals.Emit(OpCodes.Ret);

                        // GetHashCode()
                        ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0);
                        ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0);
                        ilgeneratorGetHashCode.Emit(OpCodes.Ret);

                        // ToString()
                        ilgeneratorToString.Emit(OpCodes.Ldloc_0);
                        ilgeneratorToString.Emit(OpCodes.Ldstr, names.Length == 0 ? "{ }" : " }");
                        ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString);
                        ilgeneratorToString.Emit(OpCodes.Pop);
                        ilgeneratorToString.Emit(OpCodes.Ldloc_0);
                        ilgeneratorToString.Emit(OpCodes.Callvirt, ObjectToString);
                        ilgeneratorToString.Emit(OpCodes.Ret);

                        type = tb.CreateType();

                        type = GeneratedTypes.GetOrAdd(key, type);
                    }
                }
            }

            if (types.Length != 0)
            {
                type = type.MakeGenericType(types);
            }

            return(type);
        }
Beispiel #52
0
        static System.Type ResolveType(string typeFullName, Dictionary <string, TypeBuilder> typeBuilders)
        {
            System.Type resolvedType = null;
            if (typeFullName == "Java.Lang.Object")
            {
                return(typeof(object));
            }
            else if (typeFullName == "Android.Runtime.IJavaObject" ||
                     typeFullName == "Java.Interop.IJavaObjectEx")
            {
                // Classes bound to Java APIs implement these interfaces.
                // It's safe to discard them in the portable assembly.
                return(null);
            }
            else if (typeFullName == "Java.Util.IEventListener" ||
                     typeFullName == "Java.IO.ISerializable")
            {
                // IEventListener and ISerializable are just tagging interfaces with no methods,
                // so they are save to discard.
                return(null);
            }
            else if (typeFullName == "Java.Util.EventObject")
            {
                // EventObject is a base class for Java events. It has a getSource() method.
                // TODO: Consider generating a GetSource() method when discarding this base class.
                return(typeof(System.Object));
            }
            else if (typeFullName.EndsWith("]"))
            {
                ////Log.Normal("Resolving array type " + typeFullName);
                if (typeFullName.IndexOfAny(new char[] { '*', ',' }) >= 0 ||
                    typeFullName.IndexOf(']') < typeFullName.Length - 1)
                {
                    throw new NotSupportedException("Multi-dimensional and jagged arrays are not supported.");
                }

                string      elementTypeFullName = typeFullName.Substring(0, typeFullName.IndexOf('['));
                System.Type elementType         = ResolveType(elementTypeFullName, typeBuilders);
                resolvedType = elementType.MakeArrayType();
            }
            else if (typeFullName.EndsWith(">"))
            {
                ////Log.Normal("Resolving generic type " + typeFullName);

                int    ltIndex          = typeFullName.IndexOf('<');
                string genericArguments = typeFullName.Substring(ltIndex + 1, typeFullName.Length - ltIndex - 2);
                IEnumerable <string> genericArgumentTypeFullNames = genericArguments.Split(',').Select(t => t.Trim());
                System.Type[]        genericArgumentTypes         = genericArgumentTypeFullNames.Select(
                    t => ResolveType(t, typeBuilders)).ToArray();

                string genericTypeDefinitionFullName = typeFullName.Substring(0, ltIndex) +
                                                       '`' + genericArgumentTypes.Length;
                System.Type genericDefinition = ResolveType(genericTypeDefinitionFullName, typeBuilders);

                resolvedType = genericDefinition.MakeGenericType(genericArgumentTypes);
            }
            else if (typeBuilders.ContainsKey(typeFullName))
            {
                ////Log.Normal("Resolving type " + typeFullName + " from emitted module.");
                TypeBuilder resolvedTypeBuilder;
                typeBuilders.TryGetValue(typeFullName, out resolvedTypeBuilder);
                resolvedType = resolvedTypeBuilder;
            }
            else if (!(typeFullName.StartsWith("Android.") || typeFullName.StartsWith("Java.")))
            {
                ////Log.Normal("Resolving type " + typeFullName + " from BCL.");
                resolvedType = System.Type.GetType(typeFullName, false);
                if (resolvedType == null)
                {
                    // Also check in the "System" assembly in addition to mscorlib.
                    resolvedType = typeof(System.Uri).Assembly.GetType(typeFullName, false);
                }
            }

            if (resolvedType == null)
            {
                throw new InvalidOperationException("Failed to resolve type: " + typeFullName);
            }

            return(resolvedType);
        }
Beispiel #53
0
        internal static MethodInfo GetDeepCloneForArray(System.Type elementType)
        {
            MethodInfo info = null;

            foreach (MethodInfo info2 in from m in typeof(CloneHelper).GetMethods()
                     where m.Name.Equals("DeepClone") && (m.GetGenericArguments().Length == 1)
                     select m)
            {
                MethodInfo    info3         = info2.MakeGenericMethod(new System.Type[] { elementType });
                ParameterInfo info4         = info3.GetParameters()[0];
                System.Type   type          = typeof(List <>);
                System.Type[] typeArguments = new System.Type[] { elementType };
                System.Type   c             = typeof(Enumerable).GetMethod("ToArray").MakeGenericMethod(new System.Type[] { elementType }).Invoke(null, new object[] { Activator.CreateInstance(type.MakeGenericType(typeArguments)) }).GetType();
                if (info4.ParameterType.IsAssignableFrom(c))
                {
                    info = info3;
                }
            }
            return(info);
        }
        internal Type Resolve(Func <AssemblyName, Assembly> assemblyResolver, Func <Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase)
        {
            Assembly asm = null;

            if (assemblyResolver == null && typeResolver == null)
            {
                return(Type.GetType(name, throwOnError, ignoreCase));
            }

            if (assembly_name != null)
            {
                if (assemblyResolver != null)
                {
                    asm = assemblyResolver(new AssemblyName(assembly_name));
                }
                else
                {
                    asm = Assembly.Load(assembly_name);
                }

                if (asm == null)
                {
                    if (throwOnError)
                    {
                        throw new FileNotFoundException("Could not resolve assembly '" + assembly_name + "'");
                    }
                    return(null);
                }
            }

            Type type = null;

            if (typeResolver != null)
            {
                type = typeResolver(asm, name, ignoreCase);
            }
            if (type == null)
            {
                if (throwOnError)
                {
                    throw new TypeLoadException("Could not resolve type '" + name + "'");
                }
                return(null);
            }

            if (nested != null)
            {
                foreach (var n in nested)
                {
                    var tmp = type.GetNestedType(n, BindingFlags.Public | BindingFlags.NonPublic);
                    if (tmp == null)
                    {
                        if (throwOnError)
                        {
                            throw new TypeLoadException("Could not resolve type '" + n + "'");
                        }
                        return(null);
                    }
                    type = tmp;
                }
            }

            if (generic_params != null)
            {
                Type[] args = new Type [generic_params.Count];
                for (int i = 0; i < args.Length; ++i)
                {
                    var tmp = generic_params [i].Resolve(assemblyResolver, typeResolver, throwOnError, ignoreCase);
                    if (tmp == null)
                    {
                        if (throwOnError)
                        {
                            throw new TypeLoadException("Could not resolve type '" + generic_params [i].name + "'");
                        }
                        return(null);
                    }
                    args [i] = tmp;
                }
                type = type.MakeGenericType(args);
            }

            if (array_spec != null)
            {
                foreach (var arr in array_spec)
                {
                    type = arr.Resolve(type);
                }
            }

            for (int i = 0; i < pointer_level; ++i)
            {
                type = type.MakePointerType();
            }

            if (is_byref)
            {
                type = type.MakeByRefType();
            }

            return(type);
        }
        public void Merge(MergableElement baseElement)
        {
            foreach (PropertyInfo property in GetType().GetProperties())
            {
                if (Unmergables.Contains(property.Name))
                {
                    continue;
                }
                if (property.PropertyType.IsArray)
                {
                    Array values     = (Array)property.GetValue(this);
                    Array baseValues = (Array)property.GetValue(baseElement);
                    if (values == null)
                    {
                        property.SetValue(this, baseValues);
                        continue;
                    }
                    if (baseValues == null)
                    {
                        continue;
                    }

                    bool  mergable = typeof(MergableElement).IsAssignableFrom(values.GetType().GetElementType());
                    IList result   = MakeList(values.GetType().GetElementType());
                    foreach (object value in values)
                    {
                        if (mergable)
                        {
                            MergableElement baseValue = baseValues.OfType <MergableElement>().FirstOrDefault(m => m.Equals(value));
                            if (baseValue != null)
                            {
                                ((MergableElement)value).Merge(baseValue);
                            }
                        }
                        result.Add(value);
                    }

                    foreach (object additional in baseValues.Cast <object>().Except(values.Cast <object>()))
                    {
                        result.Add(additional);
                    }

                    property.SetValue(this, result.GetType().GetMethod("ToArray")?.Invoke(result, Array.Empty <object>()));
                }
                else
                {
                    object value     = property.GetValue(this);
                    object baseValue = property.GetValue(baseElement);
                    property.SetValue(this, MergeValues(value, baseValue, this.IsSpecified(property.Name)));
                }
            }

            IList MakeList(System.Type type)
            {
                System.Type listType            = typeof(List <>);
                System.Type constructedListType = listType.MakeGenericType(type);

                return((IList)Activator.CreateInstance(constructedListType));
            }

            object MergeValues(object value, object baseValue, bool specified)
            {
                if (value is MergableElement mergableElement &&
                    baseValue is MergableElement baseMergableElement)
                {
                    mergableElement.Merge(baseMergableElement);
                    return(mergableElement);
                }

                return(!specified ? baseValue : value);
            }
        }
Beispiel #56
0
        public virtual object GetRealObject(StreamingContext context)
        {
            switch (this.m_unityType)
            {
            case 1:
                return(Empty.Value);

            case 2:
                return(DBNull.Value);

            case 3:
                return(Missing.Value);

            case 4:
            {
                if (this.m_data == null || this.m_data.Length == 0)
                {
                    this.ThrowInsufficientInformation("Data");
                }
                if (this.m_assemblyName == null)
                {
                    this.ThrowInsufficientInformation("AssemblyName");
                }
                if (this.m_assemblyName.Length == 0)
                {
                    return(Type.GetType(this.m_data, true, false));
                }
                Assembly assembly = Assembly.Load(this.m_assemblyName);
                return(assembly.GetType(this.m_data, true, false));
            }

            case 5:
            {
                if (this.m_data == null || this.m_data.Length == 0)
                {
                    this.ThrowInsufficientInformation("Data");
                }
                if (this.m_assemblyName == null)
                {
                    this.ThrowInsufficientInformation("AssemblyName");
                }
                Assembly assembly = Assembly.Load(this.m_assemblyName);
                Module   module   = assembly.GetModule(this.m_data);
                if (module == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnableToFindModule", new object[]
                        {
                            this.m_data,
                            this.m_assemblyName
                        }));
                }
                return(module);
            }

            case 6:
                if (this.m_data == null || this.m_data.Length == 0)
                {
                    this.ThrowInsufficientInformation("Data");
                }
                if (this.m_assemblyName == null)
                {
                    this.ThrowInsufficientInformation("AssemblyName");
                }
                return(Assembly.Load(this.m_assemblyName));

            case 7:
                if (this.m_declaringMethod == null && this.m_declaringType == null)
                {
                    this.ThrowInsufficientInformation("DeclaringMember");
                }
                if (this.m_declaringMethod != null)
                {
                    return(this.m_declaringMethod.GetGenericArguments()[this.m_genericParameterPosition]);
                }
                return(this.MakeElementTypes(this.m_declaringType.GetGenericArguments()[this.m_genericParameterPosition]));

            case 8:
            {
                this.m_unityType = 4;
                Type type = this.GetRealObject(context) as Type;
                this.m_unityType = 8;
                if (this.m_instantiation[0] == null)
                {
                    return(null);
                }
                return(this.MakeElementTypes(type.MakeGenericType(this.m_instantiation)));
            }

            default:
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
            }
        }
Beispiel #57
0
 public override IQueryable <T> CreateQuery <T>(Expression expression)
 {
     return((IQueryable <T>)Activator.CreateInstance(_queryableType.MakeGenericType(typeof(T)), this, expression, _client));
 }