public RecordInfo(Type type) { if (!typeof(Record).IsAssignableFrom(type)) { throw new ArgumentException("Record type is not derived from Record: " + type.FullName); } var attribute = type.GetCustomAttributes(typeof(RecordAttribute), false).Cast<RecordAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>(); if (attribute == null) { throw new ArgumentException("Record type is missing required atribute: " + type.FullName); } signature = attribute.Signature; var va = type.GetCustomAttributes(typeof(VersionAttribute), false).Cast<VersionAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>(); if (va != null) { version = va.Version; } var da = type.GetCustomAttributes(typeof(DummyAttribute), false).Cast<DummyAttribute>().FirstOrDefault(); isDummyRecord = da != null; ctor = type.GetConstructor(paramlessTypes); compound = InfoProvider.GetCompoundInfo(type); }
public NewExpr(Type type, List<HostArg> args, IPersistentMap spanMap) { _args = args; _type = type; _spanMap = spanMap; _ctor = ComputeCtor(); }
internal InterfaceObject(Type tp) : base(tp) { CoClassAttribute coclass = (CoClassAttribute) Attribute.GetCustomAttribute(tp, cc_attr); if (coclass != null) { ctor = coclass.CoClass.GetConstructor(Type.EmptyTypes); } }
public AliasToBeanResultTransformer(System.Type resultClass) { if (resultClass == null) { throw new ArgumentNullException("resultClass"); } this.resultClass = resultClass; constructor = resultClass.GetConstructor(flags, null, System.Type.EmptyTypes, null); // if resultClass is a ValueType (struct), GetConstructor will return null... // in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances if (constructor == null && resultClass.IsClass) { throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor", "resultClass"); } propertyAccessor = new ChainedPropertyAccessor(new[] { PropertyAccessorFactory.GetPropertyAccessor(null), PropertyAccessorFactory.GetPropertyAccessor("field") }); }
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() }; }
private static void DemandMemberAccessIfNeeded(ConstructorInfo constructor) { if (!constructor.IsVisible()) { DemandMemberAccess(constructor); } }
public void Init() { m_PropInstance = new PropertiesTestType(); m_DefaultConstructor = m_TypeUnderTest.GetConstructor(Type.EmptyTypes); m_PropInstanceMeta = new ObjectInstance(m_PropInstance, new ObjectCreationData(m_DefaultConstructor)); m_ConstructorTest = new ConstructorTest(TimeSpan.FromMilliseconds(1), m_DefaultConstructor, m_PropInstance); }
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; }
internal CustomAttributeData(Module scope, CustomAttributeRecord caRecord) { this.m_scope = scope; this.m_ctor = (ConstructorInfo) RuntimeType.GetMethodBase(scope, (int) caRecord.tkCtor); ParameterInfo[] parametersNoCopy = this.m_ctor.GetParametersNoCopy(); this.m_ctorParams = new CustomAttributeCtorParameter[parametersNoCopy.Length]; for (int i = 0; i < parametersNoCopy.Length; i++) { this.m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType(parametersNoCopy[i].ParameterType, scope)); } FieldInfo[] fields = this.m_ctor.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] properties = this.m_ctor.DeclaringType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); this.m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length]; for (int j = 0; j < fields.Length; j++) { this.m_namedParams[j] = new CustomAttributeNamedParameter(fields[j].Name, CustomAttributeEncoding.Field, InitCustomAttributeType(fields[j].FieldType, scope)); } for (int k = 0; k < properties.Length; k++) { this.m_namedParams[k + fields.Length] = new CustomAttributeNamedParameter(properties[k].Name, CustomAttributeEncoding.Property, InitCustomAttributeType(properties[k].PropertyType, scope)); } this.m_members = new MemberInfo[fields.Length + properties.Length]; fields.CopyTo(this.m_members, 0); properties.CopyTo(this.m_members, fields.Length); CustomAttributeEncodedArgument.ParseAttributeArguments(caRecord.blob, ref this.m_ctorParams, ref this.m_namedParams, this.m_scope); }
protected override Expression VisitNew(NewExpression node) { var originalConstructorParameters = node.Arguments.Select(x => x.Type).ToList(); var genericType = node.Constructor.DeclaringType.GetGenericTypeDefinition(); var genericTypeParameters = genericType.GetTypeInfo().GenericTypeArguments.ToList(); var originalGenericArgs = node.Constructor.DeclaringType.GetTypeInfo().GenericTypeArguments.ToList(); if (genericTypeParameters.Count != _newGenericArgs.Length) { throw new InvalidOperationException("Wrong number of generic argument values specified. This type requires " + genericTypeParameters.Count + " generic type arguments"); } for (int i = 0; i < _newGenericArgs.Length; i++) { var constraints = genericTypeParameters[i].GetTypeInfo().GetGenericParameterConstraints().ToList(); foreach (var constraint in constraints) { if (!constraint.GetTypeInfo().IsAssignableFrom(_newGenericArgs[i].GetTypeInfo())) { throw new InvalidOperationException("Generic type parameter " + i + " is constrained to type " + constraint + ". The supplied type " + _newGenericArgs[i] + " does not meet this constraint"); } } } result = genericType.MakeGenericType(_newGenericArgs.ToArray()).GetTypeInfo().DeclaredConstructors.Where(x => x == node.Constructor).Single(); throw new VisitStoppedException(); }
public ConstructorMap(ConstructorInfo ctor, IEnumerable<ConstructorParameterMap> ctorParams) { Ctor = ctor; CtorParams = ctorParams; _runtimeCtor = DelegateFactory.CreateCtor(ctor, CtorParams); }
protected override ArgumentReference[] GetCtorArgumentsAndBaseCtorToCall(Type targetFieldType, ProxyGenerationOptions proxyGenerationOptions,out ConstructorInfo baseConstructor) { if (proxyGenerationOptions.Selector == null) { baseConstructor = InvocationMethods.CompositionInvocationConstructorNoSelector; return new[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(MethodInfo)), new ArgumentReference(typeof(object[])), }; } baseConstructor = InvocationMethods.CompositionInvocationConstructorWithSelector; return new[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(MethodInfo)), new ArgumentReference(typeof(object[])), new ArgumentReference(typeof(IInterceptorSelector)), new ArgumentReference(typeof(IInterceptor[]).MakeByRefType()) }; }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { if (this.DataContext == null) return; Type objtype = null; try { objtype = (this.DataContext as PropertyValueConverter.PropertyInfo).PropertyValue.GetType().GetMethod("Add").GetParameters().FirstOrDefault().ParameterType; }catch(AmbiguousMatchException) { //WPFHelper.InvalidateControl(this, ex.Message); AddItemButton.IsEnabled = false; AddItemButton.Content = "[no suitable add]"; return; } ci = objtype.GetConstructor(Type.EmptyTypes); if (ci == null) { //last chance for strings Type[] types = {typeof(char[])}; ci = objtype.GetConstructor(types); if (ci == null) { AddItemButton.IsEnabled = false; AddItemButton.Content = "[no default constructor]"; } } }
internal SerializableImplementor(EntityType ospaceEntityType) { _baseClrType = ospaceEntityType.ClrType; _baseImplementsISerializable = _baseClrType.IsSerializable && typeof(ISerializable).IsAssignableFrom(_baseClrType); if (_baseImplementsISerializable) { // Determine if interface implementation can be overridden. // Fortunately, there's only one method to check. var mapping = _baseClrType.GetInterfaceMap(typeof(ISerializable)); _getObjectDataMethod = mapping.TargetMethods[0]; // Members that implement interfaces must be public, unless they are explicitly implemented, in which case they are private and sealed (at least for C#). var canOverrideMethod = (_getObjectDataMethod.IsVirtual && !_getObjectDataMethod.IsFinal) && _getObjectDataMethod.IsPublic; if (canOverrideMethod) { // Determine if proxied type provides the special serialization constructor. // In order for the proxy class to properly support ISerializable, this constructor must not be private. _serializationConstructor = _baseClrType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); _canOverride = _serializationConstructor != null && (_serializationConstructor.IsPublic || _serializationConstructor.IsFamily || _serializationConstructor.IsFamilyOrAssembly); } Debug.Assert( !(_canOverride && (_getObjectDataMethod == null || _serializationConstructor == null)), "Both GetObjectData method and Serialization Constructor must be present when proxy overrides ISerializable implementation."); } }
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)); }
// public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues) { InitCustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues); }
internal NewExpression (ConstructorInfo constructor, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members) : base (ExpressionType.New, constructor.DeclaringType) { this.constructor = constructor; this.arguments = arguments; this.members = members; }
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)); }
internal void InvokeBaseConstructor(ConstructorInfo constructor, params ArgumentReference[] arguments) { AddStatement( new ExpressionStatement( new ConstructorInvocationExpression(constructor, ArgumentsUtil.ConvertArgumentReferenceToExpression(arguments)))); }
/// <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 void Check(ConstructorInfo info, Dependency parent) { if (info.IsPrivate && !info.ReflectedType.IsAbstract) { parent.Add(new ProblemDependency(string.Format("This is a private constructor"))); } }
public DataRowKeyInfoHelper(Type type) { this.type = type; this.properties = type .GetProperties() .Select(p => new { Property = p, Attribute = p.GetCustomAttributes(false) .OfType<DataRowPropertyAttribute>() .SingleOrDefault() }) .Where(x => x.Attribute != null) .OrderBy(x => x.Attribute.Index) .Select(x => x.Property) .ToArray(); this.ctor = type .GetConstructors() .Single(); this.isLarge = this.type .GetCustomAttributes(false) .OfType<LargeDataRowAttribute>() .Any(); }
public NullableMembers(Type elementType) { NullableType = NullableTypeDefinition.MakeGenericType(elementType); Constructor = NullableType.GetConstructor(new[] { elementType }); GetHasValue = NullableType.GetProperty("HasValue").GetGetMethod(); GetValue = NullableType.GetProperty("Value").GetGetMethod(); }
public static IEntity Build(Mobile from, ConstructorInfo ctor, object[] values, string[,] props, PropertyInfo[] realProps, ref bool sendError) { object built = ctor.Invoke(values); if (built != null && realProps != null) { bool hadError = false; for (int i = 0; i < realProps.Length; ++i) { if (realProps[i] == null) continue; string result = Properties.InternalSetValue(from, built, built, realProps[i], props[i, 1], props[i, 1], false); if (result != "Property has been set.") { if (sendError) from.SendMessage(result); hadError = true; } } if (hadError) sendError = false; } return (IEntity)built; }
public bool GetCustomAttribute(out System.Reflection.ConstructorInfo attributeCtor, out byte[] blob) { attributeCtor = null; blob = null; try { // Get ctor Assembly assembly = Assembly.Load(m_assemblyName); Type type = assembly.GetType(m_typeName); ConstructorInfo[] ctors = type.GetConstructors(); foreach (ConstructorInfo ctor in ctors) { if (ctor.ToString().Equals(m_constructor)) { attributeCtor = ctor; break; } } if (attributeCtor == null) { return(false); } return(GetBlobByString(m_data, out blob)); } catch (Exception) { return(false); } }
public object CreateObject(string typeName, object[] arguments) { object createdObject = null; System.Type[] argumentTypes = null; if (arguments == null || arguments.GetLength(0) == 0) { argumentTypes = System.Type.EmptyTypes; } else { argumentTypes = arguments.Select(p => p.GetType()).ToArray(); } System.Type typeToConstruct = Assembly.GetType(typeName); System.Reflection.ConstructorInfo constructorInfoObj = typeToConstruct.GetConstructor(argumentTypes); if (constructorInfoObj == null) { Debug.Assert(false, "DynamicAssembly.CreateObject Failed to get the constructorInfoObject"); } else { createdObject = constructorInfoObj.Invoke(arguments); } Debug.Assert(createdObject != null); return(createdObject); }
public void ReturnCodeExceptions() { Type[] list = { typeof(DISCOVERY_RESULT /*_SocketException*/), typeof(PORT_RETURN_CODE /*_WidcommSocketException*/), typeof(REM_DEV_INFO_RETURN_CODE /*_WidcommSocketException*/), typeof(SdpService.SDP_RETURN_CODE /*_WidcommSocketException*/), }; // Type baseType = typeof(WidcommSocketException); Assembly baseAssm = baseType.Assembly; foreach (Type cur in list) { //Exception ex = (Exception)Activator.CreateInstance(cur, 1, RcValue, Location); string curTypeName = cur.Name; string exTypeName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "InTheHand.Net.Bluetooth.Widcomm.{0}_WidcommSocketException", curTypeName); Type exType = baseAssm.GetType(exTypeName, true); System.Reflection.ConstructorInfo[] ciList = exType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); System.Reflection.ConstructorInfo ci = exType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), cur, typeof(string) }, null); #if !NETCF int rcValue2 = RcValue; #else object rcValue2 = Enum.Parse(cur, RcValue.ToString(), false); #endif Exception ex = (Exception)ci.Invoke(new object[] { 1, rcValue2, Location }); // DoTest(ex, cur, curTypeName); // }//for }
protected static void CheckAssembly <T>(Assembly assembly, List <T> list, List <object> existing) where T : class { foreach (Type type in assembly.GetTypes()) { if (type.IsAbstract) { continue; } if (typeof(T).IsAssignableFrom(type)) { System.Reflection.ConstructorInfo constructor = type.GetConstructor(new Type[0]); if (constructor != null) { T item = constructor.Invoke(new object[0]) as T; if (item != null) { list.Add(item); if (existing != null) { existing.Add(item); } } } } } }
/// <summary> /// Get a registry key from a pointer. /// </summary> /// <param name="hKey">Pointer to the registry key</param> /// <param name="writable">Whether or not the key is writable.</param> /// <param name="ownsHandle">Whether or not we own the handle.</param> /// <returns>Registry key pointed to by the given pointer.</returns> private static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle) { //Get the BindingFlags for private contructors System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; //Get the Type for the SafeRegistryHandle Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle"); //Get the array of types matching the args of the ctor we want Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) }; //Get the constructorinfo for our object System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor( privateConstructors, null, safeRegistryHandleCtorTypes, null); //Invoke the constructor, getting us a SafeRegistryHandle Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle }); //Get the type of a RegistryKey Type registryKeyType = typeof(RegistryKey); //Get the array of types matching the args of the ctor we want Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) }; //Get the constructorinfo for our object System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor( privateConstructors, null, registryKeyConstructorTypes, null); //Invoke the constructor, getting us a RegistryKey RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable }); //return the resulting key return(resultKey); }
public void AddUsableEffectHandler(UsableEffectHandler handler) { System.Type type = handler.GetType(); if (type.GetCustomAttribute <DefaultEffectHandlerAttribute>() != null) { throw new System.Exception("Default handler cannot be added"); } EffectHandlerAttribute[] array = type.GetCustomAttributes <EffectHandlerAttribute>().ToArray <EffectHandlerAttribute>(); if (array.Length == 0) { throw new System.Exception(string.Format("EffectHandler '{0}' has no EffectHandlerAttribute", type.Name)); } System.Reflection.ConstructorInfo constructor = type.GetConstructor(new System.Type[] { typeof(EffectBase), typeof(Character), typeof(BasePlayerItem) }); if (constructor == null) { throw new System.Exception("No valid constructors found !"); } foreach (EffectsEnum current in from entry in array select entry.Effect) { this.m_usablesEffectHandler.Add(current, constructor.CreateDelegate <EffectManager.UsableEffectConstructor>()); if (!this.m_effectsHandlers.ContainsKey(current)) { this.m_effectsHandlers.Add(current, new System.Collections.Generic.List <System.Type>()); } this.m_effectsHandlers[current].Add(type); } }
public System.Reflection.ConstructorInfo GetConstructorOf(System.String fullClassName) { System.Type clazz = classPool.GetClass(fullClassName); try { // Checks if exist a default constructor - with no parameters System.Reflection.ConstructorInfo constructor = clazz.GetConstructor(new System.Type[0]); return(constructor); } catch (System.MethodAccessException e) { // else take the constructer with the smaller number of parameters // and call it will null values // @TODO Put this inf oin 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(); 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; } } System.Reflection.ConstructorInfo constructor = constructors[bestConstructorIndex]; return(constructor); } }
/// <summary> /// Creates one new blank chunk of the corresponding type, according to factoryMap (PngChunkUNKNOWN if not known) /// </summary> /// <param name="cid">Chunk Id</param> /// <param name="info"></param> /// <returns></returns> internal static PngChunk FactoryFromId(String cid, ImageInfo info) { PngChunk chunk = null; if (factoryMap == null) { initFactory(); } if (isKnown(cid)) { Type t = factoryMap[cid]; if (t == null) { System.Diagnostics.Debug.WriteLine("What?? " + cid); } System.Reflection.ConstructorInfo cons = t.GetTypeInfo().DeclaredConstructors.Single( c => { var p = c.GetParameters(); return(p.Length == 1 && p[0].ParameterType == typeof(ImageInfo)); }); object o = cons.Invoke(new object[] { info }); chunk = (PngChunk)o; } if (chunk == null) { chunk = new PngChunkUNKNOWN(cid, info); } return(chunk); }
private static object CoerceObject(object value, Type to) { if (value == null) { return(null); } var result = value; if (typeof(Select).IsAssignableFrom(to)) { var ctorChain = new List <System.Reflection.ConstructorInfo>(); System.Reflection.ConstructorInfo ctor = null; if (STEPListener.TypeHasConstructorForSelectChoice(to, value.GetType(), out ctor, ref ctorChain)) { result = ctor.Invoke(new object[] { value }); if (ctorChain.Any()) { // Construct the necessary wrappers working // backwards. For the first constructor, the parameter // will be the constructed instance. for (var y = ctorChain.Count - 1; y >= 0; y--) { result = ctorChain[y].Invoke(new object[] { result }); } } } } return(result); }
/// <summary> /// 重写LoadControl,带参数。 /// </summary> private UserControl LoadControl(string UserControlPath, params object[] constructorParameters) { List <Type> constParamTypes = new List <Type>(); foreach (object constParam in constructorParameters) { constParamTypes.Add(constParam.GetType()); } UserControl ctl = Page.LoadControl(UserControlPath) as UserControl; // Find the relevant constructor System.Reflection.ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray()); //And then call the relevant constructor if (constructor == null) { throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString()); } else { constructor.Invoke(ctl, constructorParameters); } // Finally return the fully initialized UC return(ctl); }
void ThrowIfConstructorIsInvalid(Type type, System.Reflection.ConstructorInfo constructor) { if (constructor == null) { throw new InvalidAggregateRootConstructorSignature(type); } }
/// <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; }
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; }
static SingletonFactory() { try { Type type = typeof(Singleton); System.Reflection.ConstructorInfo[] constructorInfoArray = type.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public); System.Reflection.ConstructorInfo noParameterConstructorInfo = null; foreach (System.Reflection.ConstructorInfo constructorInfo in constructorInfoArray) { System.Reflection.ParameterInfo[] parameterInfoArray = constructorInfo.GetParameters(); if (0 == parameterInfoArray.Length) { noParameterConstructorInfo = constructorInfo; break; } } if (null == noParameterConstructorInfo) { throw new NotSupportedException("No constructor without 0 parameter"); } singleton = (Singleton)noParameterConstructorInfo.Invoke(null); } catch (Exception e) { Console.WriteLine("e=" + e.ToString()); } }
public static object newInstance(System.Type t, System.Collections.Generic.IDictionary <System.Type, object> paramArray) { if (t == null) { throw new System.ArgumentNullException("t"); } int num = (paramArray == null) ? 0 : paramArray.Count; System.Type[] array = new System.Type[num]; object[] array2 = new object[num]; if (num > 0) { System.Collections.Generic.IEnumerator <System.Type> enumerator = paramArray.Keys.GetEnumerator(); int num2 = 0; while (enumerator.MoveNext()) { array[num2] = enumerator.Current; array2[num2] = paramArray[array[num2]]; num2++; } } System.Reflection.ConstructorInfo constructor = t.GetConstructor(array); if (constructor == null) { throw new System.Exception(); } return(constructor.Invoke(array2)); }
public IEnumerable<object> GetArguments(ConstructorInfo constructorInfo) { if (!_constructorArguments.ContainsKey(constructorInfo)) return null; return _constructorArguments[constructorInfo]; }
/// <summary> /// Crea una instancia de un Lbl.ElementoDeDatos a partir de un registro de base de datos. /// </summary> public static T Instanciar <T>(Lfx.Data.IConnection dataBase, Lfx.Data.Row row) where T : Lbl.ElementoDeDatos { Type tipo = typeof(T); System.Reflection.ConstructorInfo TConstr = tipo.GetConstructor(new Type[] { typeof(Lfx.Data.Connection), typeof(Lfx.Data.Row) }); return((T)(TConstr.Invoke(new object[] { dataBase, row }))); }
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; }
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(); }
public static void AddCustomSize(SizeType sizeType, int width, int height, string baseText) { // Create a new game view size var sizesType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSize"); var gameviewsizetypeType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSizeType"); System.Reflection.ConstructorInfo constructor = sizesType.GetConstructor(new System.Type[] { gameviewsizetypeType, typeof(int), typeof(int), typeof(string) }); object customGameViewSize = constructor.Invoke(new object[] { (int)sizeType, width, height, baseText }); // Add it to the view size group object group = GetGroup(); System.Reflection.MethodInfo addCustomSize = group.GetType().GetMethod("AddCustomSize"); addCustomSize.Invoke(group, new object[] { customGameViewSize }); }
public ConstructorMap(ConstructorInfo ctor, IEnumerable<ConstructorParameterMap> ctorParams) { Ctor = ctor; CtorParams = ctorParams; _runtimeCtor = new Lazy<LateBoundParamsCtor>(() => DelegateFactory.CreateCtor(ctor, CtorParams)); }
/// <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); }
/// <summary> ///Get Accounting Class /// </summary> /// <param name="ass">accounting schema array</param> /// <param name="dr">result set</param> /// <param name="trxName">trx</param> /// <returns>instance or null</returns> public AccountingInterface GetAccountingInstance(MAcctSchema[] ass, DataRow dr, Trx trxName) { //Class<?> clazz = getAccountingClass(); Type clazz = GetAccountingClass(); if (clazz == null) { return(null); } try { //Constructor<?> constr = clazz.getConstructor(MAcctSchema[].class, ResultSet.class, String.class); System.Reflection.ConstructorInfo constr = clazz.GetConstructor(new Type[] { typeof(MAcctSchema[]), typeof(DataRow), typeof(Trx) }); log.Info(constr.Name + ": Constructor check "); //AccountingInterface retValue = (AccountingInterface)constr.newInstance(ass, rs, trxName); AccountingInterface retValue = (AccountingInterface)constr.Invoke(new object[] { ass, dr, trxName }); log.Info(retValue.ToString() + ": Constructor invoke check "); return(retValue); } catch (Exception e) { log.Warning("Error instanciating " + GetName() + ": - " + e.ToString()); } return(null); }
public override object ConvertTo( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object Value, Type destinationType) { if (destinationType.Equals(typeof(InstanceDescriptor))) { DotNetAssemblyInfo info = ( DotNetAssemblyInfo )Value; System.Reflection.ConstructorInfo ctor = typeof(DotNetAssemblyInfo).GetConstructor( new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(AssemblyNameFlags) }); return(new InstanceDescriptor( ctor, new object[] { info.Name, info.VersionString, info.RuntimeVersionString, info.CodeBase, info.FileName, info.Flags }, true)); } return(base.ConvertTo(context, culture, Value, destinationType)); }
/// <summary> 检查指定类型中是否包含指定构造函数 Type[] parameters = { typeof(string),typeof(DataTable) }</summary> public static bool IsHaveParamConstruct(this object obj, Type[] parameters) { Type t = obj.GetType(); System.Reflection.ConstructorInfo ci = t.GetConstructor(parameters); return(ci != null); }
/// <summary> Used to Convert an RfcLdapMessage object to the appropriate /// LdapExtendedResponse object depending on the operation being performed. /// /// </summary> /// <param name="inResponse"> The LdapExtendedReponse object as returned by the /// extendedOperation method in the LdapConnection object. /// </param> /// <returns> An object of base class LdapExtendedResponse. The actual child /// class of this returned object depends on the operation being /// performed. /// </returns> static public LdapExtendedResponse convertToExtendedResponse(RfcLdapMessage inResponse) { LdapExtendedResponse tempResponse = new LdapExtendedResponse(inResponse); // Get the oid stored in the Extended response System.String inOID = tempResponse.ID; RespExtensionSet regExtResponses = LdapExtendedResponse.RegisteredResponses; try { System.Type extRespClass = regExtResponses.findResponseExtension(inOID); if (extRespClass == null) { return(tempResponse); } System.Type[] argsClass = new System.Type[] { typeof(RfcLdapMessage) }; System.Object[] args = new System.Object[] { inResponse }; System.Exception ex; try { System.Reflection.ConstructorInfo extConstructor = extRespClass.GetConstructor(argsClass); try { System.Object resp = null; resp = extConstructor.Invoke(args); return((LdapExtendedResponse)resp); } catch (System.UnauthorizedAccessException e) { ex = e; } catch (System.Reflection.TargetInvocationException e) { ex = e; } catch (System.Exception e) { // Could not create the ResponseControl object // All possible exceptions are ignored. We fall through // and create a default LdapControl object ex = e; } } catch (System.MethodAccessException e) { // bad class was specified, fall through and return a // default LdapExtendedResponse object ex = e; } } catch (System.FieldAccessException e) { } // If we get here we did not have a registered extendedresponse // for this oid. Return a default LdapExtendedResponse object. return(tempResponse); }
public IReflectedClassBuilder ExportConstructor(SysReflection.ConstructorInfo info) { if (info.DeclaringType != typeof(T)) { throw new ArgumentException("info must belong to the current class"); } _constructors.Add(info); return(this); }
private IHasName GetChild(Type childType, string name) { if (childType != null && name != null) { System.Reflection.ConstructorInfo ci = childType.GetConstructor(new Type[] { typeof(string) }); IHasName child = ci.Invoke(new object[] { name }) as IHasName; return(child); } return(null); }
/// <summary> /// Initialize this provider to be able to gets the intialization value. /// </summary> private void Initialize() { if (!_initialized) { _initialized = true; #if ACTIVEX_COMPONENTSERVER if (_elementType.BaseType.Name == "ComponentClassHelper" || _elementType.BaseType.Name == "ComponentSingleUseClassHelper" || _elementType.BaseType.Name == "GlbComponentSingleUseClassHelper") { _initializeMethod = InitialValueMethod.CsFactory; } else #endif if (_elementType == typeof(Object)) { _initializeMethod = InitialValueMethod.Null; } else if (!(_elementType == typeof(String))) { //try for a constructor method if (_constructorParams == null) { _constructorParams = new object[] { } } ; #if PORTABLE Type[] typeArray = new Type[_constructorParams.Length]; for (int i = 0; i < _constructorParams.Length; i++) { typeArray[i] = _constructorParams[i].GetType(); } #else Type[] typeArray = Type.GetTypeArray(_constructorParams); #endif if ((_constructor = _elementType.GetConstructor(typeArray)) == null) { if (_elementType.IsValueType && (_constructorParams == null || _constructorParams.Length == 0)) { _initializeMethod = (_method = _elementType.GetMethod("CreateInstance")) == null ? InitialValueMethod.ValueType : InitialValueMethod.CreateInstanceValueType; } } else { _initializeMethod = InitialValueMethod.Constructor; } } } } }
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 ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(InstanceDescriptor)) { System.Reflection.ConstructorInfo ci = typeof(ParalaxBackground).GetConstructor( System.Type.EmptyTypes); return(new InstanceDescriptor(ci, null, false)); } return(base.ConvertTo(context, culture, value, destType)); }
public static System.Func <Type> CreateDelegate <Type>(System.Type type) { if (type == null) { throw new System.ArgumentNullException(nameof(type)); } var typeInfo = type.GetTypeInfo(); if (typeInfo.IsInterface) { throw new System.ArgumentException(string.Format("{0} is an interface.", type), nameof(type)); } if (typeInfo.IsAbstract) { throw new System.ArgumentException(string.Format("{0} is abstract.", type), nameof(type)); } System.Reflection.ConstructorInfo constructorInfo = null; if (typeInfo.IsClass) { constructorInfo = type.GetConstructor(System.Type.EmptyTypes); if (constructorInfo == null) { throw new System.ArgumentException(string.Format("{0} does not have a public parameterless constructor.", type), nameof(type)); } } var dynamicMethod = EmitUtils.CreateDynamicMethod(string.Format("{0}_{1}", "$Create", type), typeof(Type), System.Type.EmptyTypes, type); var il = dynamicMethod.GetILGenerator(); if (typeInfo.IsClass) { il.Newobj(constructorInfo); } else { il.DeclareLocal(type); il.LoadLocalVariableAddress(0); il.Initobj(type); il.LoadLocalVariable(0); il.Box(type); } il.Ret(); return((System.Func <Type>)dynamicMethod.CreateDelegate(typeof(System.Func <Type>))); }
public void AddSpellCastHandler(System.Type handler, SpellTemplate spell) { System.Reflection.ConstructorInfo constructor = handler.GetConstructor(new System.Type[] { typeof(FightActor), typeof(Spell), typeof(Cell), typeof(bool) }); if (constructor == null) { throw new System.Exception(string.Format("Handler {0} : No valid constructor found !", handler.Name)); } this.m_spellsCastHandler.Add(spell.Id, constructor.CreateDelegate <SpellManager.SpellCastConstructor>()); }
/// <summary> /// This method constructs a language service given the guid found in the /// registry associated with this package. The default implementation assumes /// the guid is registered and uses Type.GetTypeFromCLSID to construct the /// language service. You can override this method if you want to construct /// the language service directly without having to register it as a COM object. /// </summary> /// <returns></returns> public virtual ILanguageService CreateLanguageService(ref Guid guid) { Type type = Type.GetTypeFromCLSID(guid, true); if (type != null) { System.Reflection.ConstructorInfo ci = type.GetConstructor(new Type[0]); if (ci != null) { ILanguageService svc = (ILanguageService)ci.Invoke(new object[0]); return(svc); } } return(null); }
/// <summary>Invokes OnConstruct directly.</summary> public object ConstructInstance(object[] paramSet) { MethodBase resMethod = (OnConstruct as MethodBase); System.Reflection.ConstructorInfo ctr = resMethod as System.Reflection.ConstructorInfo; if (ctr != null) { // Actual constructor call: return(ctr.Invoke(paramSet)); } // Ordinary method: return(resMethod.Invoke(CtrInstance, paramSet)); }
public static generate_interface.typ Create_From_Menu(string name, string filename) { System.Type type = Generator_List[name]; System.Type[] param_types = new Type[1]; generate_interface.typ result = null; object[] parameters = new object[1]; param_types[0] = typeof(string); System.Reflection.ConstructorInfo constructor = type.GetConstructor(param_types); parameters[0] = filename; result = constructor.Invoke(parameters) as generate_interface.typ; return(result); }