private bool IsBetterChoice(ConstructorInfo current, ConstructorInfo candidate) { if (candidate.GetParameters().Any(x => x.ParameterType.IsSealed)) return false; return current == null || current.GetParameters().Length < candidate.GetParameters().Length; }
private static ResolvedConstructor ResolveConstructorArguments(ConstructorInfo constructor, IDummyValueCreationSession session) { Logger.Debug("Beginning to resolve constructor with {0} arguments.", constructor.GetParameters().Length); var resolvedArguments = new List<ResolvedArgument>(); foreach (var argument in constructor.GetParameters()) { object result = null; var resolvedArgument = new ResolvedArgument { WasResolved = session.TryResolveDummyValue(argument.ParameterType, out result), ResolvedValue = result, ArgumentType = argument.ParameterType }; Logger.Debug("Was able to resolve {0}: {1}.", argument.ParameterType, resolvedArgument.WasResolved); resolvedArguments.Add(resolvedArgument); } return new ResolvedConstructor { Arguments = resolvedArguments.ToArray() }; }
/// <summary> /// Gets the number of parameters that the system recognizes /// </summary> /// <param name="Constructor">Constructor to check</param> /// <param name="MappingManager">Mapping manager</param> /// <returns>The number of parameters that it has knoweledge of</returns> private static int GetParameterCount(ConstructorInfo Constructor, MappingManager MappingManager) { int Count = 0; ParameterInfo[] Parameters = Constructor.GetParameters(); foreach (ParameterInfo Parameter in Parameters) { bool Inject = true; object[] Attributes = Parameter.GetCustomAttributes(false); if (Attributes.Length > 0) { foreach (Attribute Attribute in Attributes) { if (MappingManager.GetMapping(Parameter.ParameterType, Attribute.GetType()) != null) { ++Count; Inject = false; break; } } } if (Inject) { if (MappingManager.GetMapping(Parameter.ParameterType) != null) ++Count; } } if (Count == Parameters.Length) return Count; return int.MinValue; }
public ConstructorMethod GetConstructor(ConstructorInfo constructor) { DynamicMethod dynamicConstructor = CreateDynamicConstructor(constructor); ILGenerator il = dynamicConstructor.GetILGenerator(); ParameterInfo[] parameters = constructor.GetParameters(); for (int i = 0; i < parameters.Length; i++) { il.Emit(OpCodes.Ldarg_0); switch (i) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: il.Emit(OpCodes.Ldc_I4, i); break; } il.Emit(OpCodes.Ldelem_Ref); Type paramType = parameters[i].ParameterType; il.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } il.Emit(OpCodes.Newobj, constructor); il.BoxIfNeeded(constructor.DeclaringType); il.Emit(OpCodes.Ret); return (ConstructorMethod)dynamicConstructor.CreateDelegate(typeof(ConstructorMethod)); }
public static string ToDescription(ConstructorInfo constructor) { var parameters = constructor.GetParameters(); var paramList = parameters.Select(x => { if (x.ParameterType.IsSimple()) { return "{0} {1}".ToFormat(x.ParameterType.GetTypeName(), x.Name); } else { if (parameters.Where(p => p.ParameterType == x.ParameterType).Count() > 1) { return "{0} {1}".ToFormat(x.ParameterType.GetTypeName(), x.Name); } else { return x.ParameterType.GetTypeName(); } } }).ToArray(); return "new {0}({1})".ToFormat(constructor.DeclaringType.GetTypeName(), string.Join(", ", paramList)); }
/// <summary> /// Initializes a new instance of the <see cref="ConstructorMetadata"/> class. /// </summary> /// <param name="constructorInfo">The constructor information.</param> internal ConstructorMetadata(ConstructorInfo constructorInfo) { ConstructorInfo = constructorInfo; Signature = constructorInfo.GetParameters().Select(p => p.ParameterType).ToImmutableArray(); ParameterNames = constructorInfo.GetParameters().Select(p => p.Name).ToImmutableArray(); }
public CtorInfo(ConstructorInfo constructorInfo) { Contract.Requires<ArgumentNullException>(constructorInfo != null); this.constructorInfo = constructorInfo; this.parameters = constructorInfo.GetParameters(); this.paramTypes = constructorInfo.GetParameters().Select(p => p.ParameterType).ToArray(); }
private bool IsBetterChoice(ConstructorInfo current, ConstructorInfo candidate, Type[] existingTypes) { if (current == null) return true; if (candidate.GetParameters() .Where(x => !existingTypes.Contains(x.ParameterType)) .Any(x => x.ParameterType.IsSealed && !x.ParameterType.IsArray)) return false; return current.GetParameters().Length < candidate.GetParameters().Length; }
/// <summary> /// Determines which parameter types need to be supplied to invoke a particular /// <paramref name="constructor"/> instance. /// </summary> /// <param name="constructor">The target constructor.</param> /// <param name="additionalArguments">The additional arguments that will be used to invoke the constructor.</param> /// <returns>The list of parameter types that are still missing parameter values.</returns> private static IEnumerable<INamedType> GetMissingParameterTypes(ConstructorInfo constructor, IEnumerable<object> additionalArguments) { var parameters = from p in constructor.GetParameters() select p; // Determine which parameters need to // be supplied by the container var parameterTypes = new List<INamedType>(); var argumentCount = additionalArguments.Count(); if (additionalArguments != null && argumentCount > 0) { // Supply parameter values for the // parameters that weren't supplied by the // additionalArguments var parameterCount = parameters.Count(); var maxIndex = parameterCount - argumentCount; var targetParameters = from param in parameters.Where(p => p.Position < maxIndex) select new NamedType(param) as INamedType; parameterTypes.AddRange(targetParameters); return parameterTypes; } var results = from param in parameters select new NamedType(param) as INamedType; parameterTypes.AddRange(results); return parameterTypes; }
public static DynamicStaticMethodConstructor CreateConstructor(ConstructorInfo constructor) { if (constructor == null) throw new ArgumentNullException("constructor"); var c = creatorCache[constructor] as DynamicStaticMethodConstructor; if (c.IsInstance()) return c; lock (creatorCache.SyncRoot) { var argsParameter = Expression.Parameter(typeof(object[]), "args"); var constructorParams = constructor.GetParameters(); Expression body = Expression.New( constructor, CreateParameterExpressions(constructorParams, argsParameter) ); var lambda = Expression.Lambda<DynamicStaticMethodConstructor>( Expression.Convert(body, typeof(object)), argsParameter ); c = creatorCache[constructor] as DynamicStaticMethodConstructor; if (c.IsInstance()) return c; var creator = lambda.Compile(); creatorCache.Add(constructor, creator); return creator; } }
public static string GetNameWithParameterList(ConstructorInfo mi) { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { writer.Write(mi.Name); writer.Write("("); ParameterInfo[] parameters = mi.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (i != 0) { writer.Write(", "); } writer.Write(parameters[i].ParameterType.ToString()); } if (mi.CallingConvention == CallingConventions.VarArgs) { if (parameters.Length > 0) { writer.Write(", "); } writer.Write("..."); } writer.Write(")"); return writer.ToString(); } }
private object ResolveInstance(ConstructorInfo constructor) { var parameterInfos = constructor.GetParameters(); var parameters = new List<object>(); int count = 0; Type lastParameterType = null; for (int index = 0; index < parameterInfos.Length; index++) { Type parameterType = parameterInfos[index].ParameterType; if (lastParameterType != parameterType) count = 0; IList<object> instances = ResolveAll(parameterType); // add the concrete type directly if not registered. if (instances.Count > 0) parameters.Add(instances[count++]); else if (parameterType.IsClass) parameters.Add(ResolveInstance(parameterType.GetConstructors().First())); lastParameterType = parameterType; } return constructor.Invoke(parameters.ToArray()); }
private IEnumerable<object> GetArgs(ConstructorInfo constructor, Property property) { foreach (var parameter in constructor.GetParameters()) { yield return GetArg(parameter.ParameterType, property); } }
protected virtual bool CanUseConstructor(ConstructorInfo constructor, Type viewType, Type pageDataType) { var constructorParameters = constructor.GetParameters(); return constructorParameters[0].ParameterType.IsAssignableFrom(viewType) && constructorParameters[1].ParameterType.IsAssignableFrom(pageDataType) && constructorParameters.Length == 2; }
internal NativeConstructorBuilder(ConstructorInfo cinfo) { ExportAttribute ea = (ExportAttribute) Attribute.GetCustomAttribute (cinfo, typeof (ExportAttribute)); ParameterInfo [] parms = cinfo.GetParameters (); if (ea == null && parms.Length > 0) throw new ArgumentException ("ConstructorInfo does not have a export attribute"); if (ea == null) Selector = selInit; else Selector = new Selector (ea.Selector, true).Handle; Signature = "@@:"; ParameterTypes = new Type [2 + parms.Length]; ParameterTypes [0] = typeof (IntPtr); ParameterTypes [1] = typeof (Selector); for (int i = 0; i < parms.Length; i++) { ParameterTypes [i + 2] = parms [i].ParameterType; Signature += TypeConverter.ToNative (parms [i].ParameterType); } DelegateType = CreateDelegateType (typeof (IntPtr), ParameterTypes); this.cinfo = cinfo; }
private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeDetails sourceTypeInfo, IProfileConfiguration options) { var parameters = new List<ConstructorParameterMap>(); var ctorParameters = destCtor.GetParameters(); if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled) return false; foreach (var parameter in ctorParameters) { var resolvers = new LinkedList<IValueResolver>(); var canResolve = MapDestinationPropertyToSource(options, sourceTypeInfo, parameter.GetType(), parameter.Name, resolvers); if(!canResolve && parameter.HasDefaultValue) { canResolve = true; } var param = new ConstructorParameterMap(parameter, resolvers.ToArray(), canResolve); parameters.Add(param); } typeMap.AddConstructorMap(destCtor, parameters); return true; }
public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members, bool asReference, bool baseTupleAsReference, bool forceIssueFakeHeader, bool useDynamicTypeWhenNeeded, bool supportNull) { if (ctor == null) throw new ArgumentNullException("ctor"); if (members == null) throw new ArgumentNullException("members"); this.ctor = ctor; this.members = members; this.tails = new IProtoSerializer[members.Length]; this.asReference = asReference; this.baseTupleAsReference = baseTupleAsReference; this.forceIssueFakeHeader = forceIssueFakeHeader; ParameterInfo[] parameters = ctor.GetParameters(); for(int i = 0 ; i < members.Length ; i++) { WireType wireType; Type finalType = parameters[i].ParameterType; Type itemType = null, defaultType = null; MetaType.ResolveListTypes(finalType, ref itemType, ref defaultType); Type tmp = itemType == null ? finalType : itemType; bool dynamicType = useDynamicTypeWhenNeeded && (tmp.IsInterface || tmp == typeof(object)); bool overrideSkipConstructor = i == 7; // if there are 8 class parameters the last one has to be a tuple IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, dynamicType, false, overrideSkipConstructor, supportNull), serializer; if (tail == null) throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); if (itemType != null && supportNull) { tail = new TagDecorator(NullDecorator.Tag, wireType, false, tail); tail = new NullDecorator(tail); tail = new TagDecorator(i + 1, WireType.StartGroup, false, tail); } else { tail = new TagDecorator(i + 1, wireType, false, tail); } if(itemType == null) { serializer = tail; } else { if (finalType.IsArray) { serializer = new ArrayDecorator(tail, i + 1, false, wireType, finalType, false, supportNull, asReference, false); } else { serializer = new ListDecorator(finalType, defaultType, tail, i + 1, false, wireType, true, false, supportNull, asReference, false, false); } } tails[i] = serializer; } }
private bool ConstructorCanBeCalled(ConstructorInfo cons, ParameterInfo[] methodArgs, IDivineInjector injector) { var constructorParams = cons.GetParameters() .Where(param => !injector.IsBound(param.ParameterType)) .ToArray(); return ConstructorHasAllMethodArgs(methodArgs, constructorParams); }
/// <summary> /// Construct a new ConstructorParameterBinding. /// </summary> /// <param name="ci">ConstructorInfo to bind.</param> /// <param name="availableParameters">Available parameters.</param> /// <param name="context">Context in which to construct instance.</param> public ConstructorParameterBinding( ConstructorInfo ci, IEnumerable<Parameter> availableParameters, IComponentContext context) { _canInstantiate = true; _ci = Enforce.ArgumentNotNull(ci, "ci"); if (availableParameters == null) throw new ArgumentNullException("availableParameters"); if (context == null) throw new ArgumentNullException("context"); var parameters = ci.GetParameters(); _valueRetrievers = new Func<object>[parameters.Length]; for (int i = 0; i < parameters.Length; ++i) { var pi = parameters[i]; bool foundValue = false; foreach (var param in availableParameters) { Func<object> valueRetriever; if (param.CanSupplyValue(pi, context, out valueRetriever)) { _valueRetrievers[i] = valueRetriever; foundValue = true; break; } } if (!foundValue) { _canInstantiate = false; _firstNonBindableParameter = pi; break; } } }
private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeDetails sourceTypeInfo, ProfileMap options) { var ctorParameters = destCtor.GetParameters(); if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled) return false; var ctorMap = new ConstructorMap(destCtor, typeMap); foreach (var parameter in ctorParameters) { var resolvers = new LinkedList<MemberInfo>(); var canResolve = MapDestinationPropertyToSource(options, sourceTypeInfo, destCtor.DeclaringType, parameter.GetType(), parameter.Name, resolvers); if(!canResolve && parameter.HasDefaultValue) { canResolve = true; } ctorMap.AddParameter(parameter, resolvers.ToArray(), canResolve); } typeMap.ConstructorMap = ctorMap; return true; }
public static KeyValuePair<string, Type>[] GetRequirements(ConstructorInfo constructor) { ParameterInfo[] parameters = constructor.GetParameters(); //parameters[0].IsOptional return null; }
protected virtual ConstructorCandidate CreateConstructorCandidate(ConstructorInfo constructor) { ParameterInfo[] parameters = constructor.GetParameters(); DependencyModel[] dependencies = new DependencyModel[parameters.Length]; for(int i = 0; i < parameters.Length; i++) { ParameterInfo parameter = parameters[i]; Type paramType = parameter.ParameterType; // This approach is somewhat problematic. We should use // another strategy to differentiate types and classify dependencies if (converter.IsSupportedAndPrimitiveType(paramType)) { dependencies[i] = new DependencyModel( DependencyType.Parameter, parameter.Name, paramType, false); } else { dependencies[i] = new DependencyModel( DependencyType.Service, parameter.Name, paramType, false); } } return new ConstructorCandidate(constructor, dependencies); }
public static bool HasMissingPrimitives(ConstructorInfo ctor, DependencyCollection dependencies) { return ctor .GetParameters() .Where(x => x.ParameterType.IsSimple()) .Any(param => dependencies.FindByTypeOrName(param.ParameterType, param.Name) == null); }
private static bool IsParameterMatch(ConstructorInfo ctor, Type[] expectedParamters) { var ctorParams = ctor.GetParameters(); return ctorParams.Select(p => p.ParameterType) .ToArray() .IsSequenceEqual(expectedParamters); }
public ConstructorMatcher(ConstructorInfo constructor) { _constructor = constructor; _parameters = _constructor.GetParameters(); _parameterValuesSet = new bool[_parameters.Length]; _parameterValues = new object[_parameters.Length]; }
private static ObjectActivator CreateNewActivator(ConstructorInfo constructorInfo) { ParameterInfo[] paramsInfo = constructorInfo.GetParameters(); //create a single param of type object[] ParameterExpression param = Expression.Parameter(typeof(object[]), PARAM_NAME); Expression[] argsExp = new Expression[paramsInfo.Length]; //pick each arg from the params array //and create a typed expression of them for(int i = 0; i < paramsInfo.Length; i++) { Expression index = Expression.Constant(i); Expression paramAccessorExp = Expression.ArrayIndex(param, index); Expression paramCastExp = Expression.Convert(paramAccessorExp, paramsInfo[i].ParameterType); argsExp[i] = paramCastExp; } //make a NewExpression that calls the constructor with the args we just created NewExpression newExp = Expression.New(constructorInfo, argsExp); //create a lambda with the NewExpression as body and our param object[] as arg LambdaExpression lambda = Expression.Lambda(typeof(ObjectActivator), newExp, param); //compile it ObjectActivator compiled = (ObjectActivator) lambda.Compile(); activators.Add(constructorInfo, compiled); return compiled; }
public object[] GetParameters(IBuilderContext context, Type type, string id, ConstructorInfo constructor) { ParameterInfo[] parms = constructor.GetParameters(); object[] parmsValueArray = new object[parms.Length]; for (int i = 0; i < parms.Length; ++i) { if (typeof(IEnumerable).IsAssignableFrom(parms[i].ParameterType)) { Type genericList = typeof(List<>); Type fullType = genericList.MakeGenericType(parms[i].ParameterType.GetGenericArguments()[0]); parmsValueArray[i] = Activator.CreateInstance(fullType); foreach (object o in Core.Objects.ObjectFactory.BuildAll(parms[i].ParameterType.GetGenericArguments()[0])) { ((IList)parmsValueArray[i]).Add(o); } } else { parmsValueArray[i] = Core.Objects.ObjectFactory.BuildUp(parms[i].ParameterType); } } return parmsValueArray; }
/// <summary> /// Generates one public constructor receiving /// the <see cref="IInterceptor"/> instance and instantiating a hashtable /// </summary> protected virtual EasyConstructor GenerateConstructor( ConstructorInfo baseConstructor ) { ArrayList arguments = new ArrayList(); ArgumentReference arg1 = new ArgumentReference( Context.Interceptor ); ArgumentReference arg2 = new ArgumentReference( typeof(object[]) ); arguments.Add( arg1 ); ParameterInfo[] parameters = baseConstructor.GetParameters(); if (Context.HasMixins) { arguments.Add( arg2 ); } ArgumentReference[] originalArguments = ArgumentsUtil.ConvertToArgumentReference(parameters); arguments.AddRange(originalArguments); EasyConstructor constructor = MainTypeBuilder.CreateConstructor( (ArgumentReference[]) arguments.ToArray( typeof(ArgumentReference) ) ); GenerateConstructorCode(constructor.CodeBuilder, arg1, SelfReference.Self, arg2); constructor.CodeBuilder.InvokeBaseConstructor( baseConstructor, originalArguments ); constructor.CodeBuilder.AddStatement( new ReturnStatement() ); return constructor; }
/// <summary> /// 得到构造函数委托 /// </summary> /// <param name="constructor">构造函数</param> /// <returns>返回构造函数委托</returns> public static ConstructorHandler GetCreator(this System.Reflection.ConstructorInfo constructor) { Guard.NotNull(constructor, "constructor"); ConstructorHandler ctor = constructor.DeclaringType.IsValueType ? (args) => constructor.Invoke(args) : DefaultDynamicMethodFactory.CreateConstructorMethod(constructor); ConstructorHandler handler = args => { if (args == null) { args = new object[constructor.GetParameters().Length]; } try { return(ctor(args)); } catch (TargetInvocationException ex) { throw ex.InnerException; } catch (Exception ex) { throw ex; } }; return(handler); }
private void EnsureParameters() { if (parameters == null) { parameters = constructor.GetParameters(); } }
private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeInfo sourceTypeInfo, IMappingOptions options) { var parameters = new List<ConstructorParameterMap>(); var ctorParameters = destCtor.GetParameters(); if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled) return false; foreach (var parameter in ctorParameters) { var members = new LinkedList<MemberInfo>(); if (!MapDestinationPropertyToSource(members, sourceTypeInfo, parameter.Name, options)) return false; var resolvers = members.Select(mi => mi.ToMemberGetter()); var param = new ConstructorParameterMap(parameter, resolvers.ToArray()); parameters.Add(param); } typeMap.AddConstructorMap(destCtor, parameters); return true; }
private Func<object[], object> InitializeInvoker(ConstructorInfo constructorInfo) { // Target: (object)new T((T0)parameters[0], (T1)parameters[1], ...) // parameters to execute var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); // build parameter list var parameterExpressions = new List<Expression>(); var paramInfos = constructorInfo.GetParameters(); for (int i = 0; i < paramInfos.Length; i++) { // (Ti)parameters[i] var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); var valueCast = Expression.Convert(valueObj, paramInfos[i].ParameterType); parameterExpressions.Add(valueCast); } // new T((T0)parameters[0], (T1)parameters[1], ...) var instanceCreate = Expression.New(constructorInfo, parameterExpressions); // (object)new T((T0)parameters[0], (T1)parameters[1], ...) var instanceCreateCast = Expression.Convert(instanceCreate, typeof(object)); var lambda = Expression.Lambda<Func<object[], object>>(instanceCreateCast, parametersParameter); return lambda.Compile(); }
Constructor LoadConstructor(System.Reflection.ConstructorInfo refConstructor) { Constructor constructor = new Constructor { Name = refConstructor.DeclaringType.Name, CallingConvention = refConstructor.CallingConvention, Attributes = refConstructor.Attributes, }; constructor.Parameters = refConstructor.GetParameters().Select(p => LoadParameter(p)).ToList(); return(constructor); }
public override object ActivateJob(Type jobType) { System.Reflection.ConstructorInfo candidateCtor = null; //Loop through ctor's and find the most specific ctor where map has all types. var conInfo = jobType.GetConstructors(); foreach (var i in conInfo) { var paramInfo = i.GetParameters(); List <ParameterInfo> lst = new List <ParameterInfo>(paramInfo); if (lst.TrueForAll(CompareParameterToMap)) { if (candidateCtor == null) { candidateCtor = i; } if (!object.ReferenceEquals(i, candidateCtor) && lst.Count > candidateCtor.GetParameters().) { candidateCtor = i; } } } //jobType.GetConstructors.ToList.ForEach(i => //{ // if (i.GetParameters.ToList.TrueForAll(CompareParameterToMap)) // { // if (candidateCtor == null) // candidateCtor = i; // if (!object.ReferenceEquals(i, candidateCtor) && i.GetParameters.Count > candidateCtor.GetParameters.Count) // candidateCtor = i; // } //}); if (candidateCtor == null) { //If the ctor is null, use default activator. return(base.ActivateJob(jobType)); } else { //Create a list of the parameters in order and activate List <object> ctorParameters = new List <object>(); candidateCtor.GetParameters.ToList.ForEach(i => ctorParameters.Add(ParameterMap(i.ParameterType).DynamicInvoke())); return(Activator.CreateInstance(jobType, ctorParameters.ToArray)); } }
T GetInstanceFrom(EventSourceId id, System.Reflection.ConstructorInfo constructor) { return((constructor.GetParameters()[0].ParameterType == typeof(EventSourceId) ? constructor.Invoke(new object[] { id }) : constructor.Invoke(new object[] { id.Value })) as T); }
private String GetArgValue(Assembly scope) { if (instruction.Operand == null) { return(""); } else { bool isLocalCall; string s = ""; if (instruction.Operand != null) { switch (instruction.Code.OperandType) { case OperandType.InlineField: System.Reflection.FieldInfo fOperand = ((System.Reflection.FieldInfo)instruction.Operand); s = fOperand.FieldType.FullName + " " + Helper.ProcessSpecialTypes(fOperand.ReflectedType, scope) + "::" + fOperand.Name + ""; break; case OperandType.InlineMethod: try { System.Reflection.MethodInfo mOperand = (System.Reflection.MethodInfo)instruction.Operand; String t = Helper.ProcessSpecialTypes(mOperand.ReflectedType, scope); isLocalCall = t.StartsWith("local"); if (isLocalCall) { s = mOperand.ReturnType.ToString() + " " + t + "::" + mOperand.Name + Helper.ParametersAsString(mOperand.GetParameters(), !mOperand.IsStatic); } else { s = mOperand.ReturnType.ToString() + " " + t + "::" + mOperand.Name + Helper.ParametersAsString(mOperand.GetParameters()); } } catch { try { System.Reflection.ConstructorInfo mOperand = (System.Reflection.ConstructorInfo)instruction.Operand; String t = Helper.ProcessSpecialTypes(mOperand.ReflectedType, scope); bool isDelegateCall = ((mOperand.GetMethodImplementationFlags() & System.Reflection.MethodImplAttributes.Runtime) != 0); if (isDelegateCall) { s = "delegate " + Helper.ProcessSpecialTypes(mOperand.ReflectedType, scope) + "::" + mOperand.Name + Helper.ParametersAsString(mOperand.GetParameters(), !mOperand.IsStatic); } else { isLocalCall = t.StartsWith("local"); if (isLocalCall) { s = "System.Void " + Helper.ProcessSpecialTypes(mOperand.ReflectedType, scope) + "::" + mOperand.Name + Helper.ParametersAsString(mOperand.GetParameters(), !mOperand.IsStatic); } else { s = "System.Void " + Helper.ProcessSpecialTypes(mOperand.ReflectedType, scope) + "::" + mOperand.Name + Helper.ParametersAsString(mOperand.GetParameters()); } } } catch { } } break; case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: // can assign anything, not used s = instruction.Offset.ToString(); break; case OperandType.InlineType: s = Helper.ProcessSpecialTypes((Type)instruction.Operand, scope); break; case OperandType.InlineString: s = instruction.Operand.ToString(); break; case OperandType.ShortInlineVar: s = instruction.Operand.ToString(); break; case OperandType.InlineI: case OperandType.InlineI8: case OperandType.InlineR: case OperandType.ShortInlineI: case OperandType.ShortInlineR: s = instruction.Operand.ToString(); break; case OperandType.InlineTok: if (instruction.Operand is Type) { s = ((Type)instruction.Operand).FullName; } else { s = "not supported"; } break; default: s = "not supported"; break; } } return(s); } }
public System.Object NewInstanceOf(System.Type clazz) { System.Reflection.ConstructorInfo constructor = null; constructor = classPool.GetConstrutor(OdbClassUtil.GetFullName(clazz)); if (constructor == null) { // Checks if exist a default constructor - with no parameters constructor = clazz.GetConstructor(Type.EmptyTypes); //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'" //c by cristi //constructor.setAccessible(true); if (constructor != null) { classPool.AddConstrutor(OdbClassUtil.GetFullName(clazz), constructor); } } if (constructor != null) { System.Object o = constructor.Invoke(new System.Object[0]); return(o); } if (clazz.IsValueType) { return(Activator.CreateInstance(clazz)); } else { // else take the constructer with the smaller number of parameters // and call it will null values // @TODO Put this info in cache ! if (OdbConfiguration.IsDebugEnabled(LogId)) { DLogger.Debug(clazz + " does not have default constructor! using a 'with parameter' constructor will null values"); } System.Reflection.ConstructorInfo[] constructors = clazz.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly); if (clazz.IsInterface) { //@TODO This is not a good solution to manage interface return(null); } if (constructors.Length == 0) { throw new ODBRuntimeException(NeoDatisError.ClassWithoutConstructor.AddParameter(clazz.AssemblyQualifiedName)); } int numberOfParameters = 1000; int bestConstructorIndex = 0; for (int i = 0; i < constructors.Length; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructors[i].GetParameters().Length < numberOfParameters) { bestConstructorIndex = i; } } constructor = constructors[bestConstructorIndex]; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" System.Object[] nulls = new System.Object[constructor.GetParameters().Length]; for (int i = 0; i < nulls.Length; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int32")) { nulls[i] = 0; } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int64")) { nulls[i] = 0; } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int16")) { nulls[i] = System.Int16.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //main by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.SByte")) { nulls[i] = System.SByte.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Single")) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" nulls[i] = System.Single.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Double")) { //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" nulls[i] = System.Double.Parse("0"); } else { nulls[i] = null; } } } } } } } System.Object object_Renamed = null; //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'" //c by cristi //constructor.setAccessible(true); try { object_Renamed = constructor.Invoke(nulls); } catch (System.Exception e2) { throw new ODBRuntimeException(NeoDatisError.NoNullableConstructor.AddParameter("[" + DisplayUtility.ObjectArrayToString(constructor.GetParameters()) + "]").AddParameter(clazz.AssemblyQualifiedName), e2); } return(object_Renamed); } }
public static System.Func <object[], object> CreateDelegate(System.Reflection.ConstructorInfo constructorInfo, bool validateArguments = true) { if (constructorInfo == null) { throw new System.ArgumentNullException(nameof(constructorInfo)); } var delclaringType = constructorInfo.DeclaringType.GetTypeInfo(); if (delclaringType.IsAbstract) { throw new System.ArgumentException("The declaring type of the constructor is abstract.", nameof(constructorInfo)); } var dynamicMethod = EmitUtils.CreateDynamicMethod(string.Format("{0}_{1}", "$Create", delclaringType.Name), typeof(object), new[] { typeof(object[]) }, constructorInfo.DeclaringType); var il = dynamicMethod.GetILGenerator(); var args = constructorInfo.GetParameters(); var lableValidationCompleted = il.DefineLabel(); if (!validateArguments || args.Length == 0) { il.Br_S(lableValidationCompleted); } else { var lableCheckArgumentsLength = il.DefineLabel(); il.Ldarg_0(); il.Brtrue_S(lableCheckArgumentsLength); il.ThrowArgumentsNullExcpetion("arguments"); il.MarkLabel(lableCheckArgumentsLength); il.Ldarg_0(); il.Ldlen(); il.Conv_I4(); il.LoadInt32(args.Length); il.Bge_S(lableValidationCompleted); il.ThrowArgumentsExcpetion("Not enough arguments in the argument array.", "arguments"); } il.MarkLabel(lableValidationCompleted); if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { il.Ldarg_0(); il.LoadInt32(i); il.Ldelem_Ref(); il.CastValue(args[i].ParameterType); } } il.Newobj(constructorInfo); il.Ret(); return((System.Func <object[], object>)dynamicMethod.CreateDelegate(typeof(System.Func <object[], object>))); }
public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type) { if (implementation == NullableImplementation.Default || implementation == NullableImplementation.Abstract) { ctd.BaseTypes.Add(new CodeTypeReference("INullable")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "IsNull"; prop.Type = new CodeTypeReference(typeof(bool)); prop.Attributes = MemberAttributes.Public; prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false))); ctd.Members.Add(prop); } if (implementation != NullableImplementation.Abstract) { CodeTypeDeclaration newType = new CodeTypeDeclaration("Null" + ctd.Name); newType.TypeAttributes = TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed; newType.BaseTypes.Add(new CodeTypeReference(ctd.Name)); cns.Types.Add(newType); System.Reflection.ConstructorInfo baseCtor = MainClass.GetBaseCtor(type); if (baseCtor != null) { CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Private; foreach (object o in baseCtor.GetParameters()) { ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(null)); } newType.Members.Add(ctor); } CodeMemberField field = new CodeMemberField(newType.Name, "Instance"); field.Attributes = MemberAttributes.Static | MemberAttributes.Assembly; field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(newType.Name)); newType.Members.Add(field); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "IsNull"; prop.Type = new CodeTypeReference(typeof(bool)); prop.Attributes = MemberAttributes.Public | MemberAttributes.Override; prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); newType.Members.Add(prop); CodeMemberMethod method = new CodeMemberMethod(); method.Name = "AcceptVisitor"; method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data")); method.ReturnType = new CodeTypeReference(typeof(object)); method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); newType.Members.Add(method); method = new CodeMemberMethod(); method.Name = "ToString"; method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.ReturnType = new CodeTypeReference(typeof(string)); method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("[" + newType.Name + "]"))); newType.Members.Add(method); prop = new CodeMemberProperty(); prop.Name = "Null"; prop.Type = new CodeTypeReference(ctd.Name); prop.Attributes = MemberAttributes.Public | MemberAttributes.Static; if (implementation == NullableImplementation.Shadow) { prop.Attributes |= MemberAttributes.New; } CodeExpression ex = new CodeTypeReferenceExpression(newType.Name); ex = new CodePropertyReferenceExpression(ex, "Instance"); prop.GetStatements.Add(new CodeMethodReturnStatement(ex)); ctd.Members.Add(prop); } }