private void Test_Load(object sender, EventArgs e) { _attType = typeof(AsyncStateMachineAttribute); _assemblies = AppDomain.CurrentDomain.GetAssemblies(); _ignoreList = new[] { "Equals", "GetHashCode", "GetType", "ToString" }; _cboCategories = new Dictionary<int, string> { { 1, "EF" }, { 2, "RPC" }, { 3, "BAL" } }; cboCategories.DataSource = new BindingSource(_cboCategories, null); cboCategories.DisplayMember = "Value"; cboCategories.ValueMember = "Key"; //cboCategories.SelectedIndex = 0; _state = new State(); var uow = new TekTak.iLoop.UOW.UnitOfWork(); _constorInfo = new ConstructorInfo { ConstorParamType = new[] { uow.GetServices().GetType() }, ConstorParams = new object[] { uow.GetServices() } }; LoadState(); _samples = API.SampleConfig.GetSamples(); cboClasses.SelectedIndex = cboClasses.Items.Count >= _state.Combo ? _state.Combo : 0; if (treeMethods.Nodes.Count > 0) treeMethods.SelectedNode = treeMethods.Nodes.Count > _state.Node ? treeMethods.Nodes[_state.Node] : treeMethods.Nodes[0]; treeMethods.Focus(); }
static Pages_ReportLauncher() { _sendEmailMaint = System.Web.Compilation.BuildManager.GetType(_SENDEMAILMAINT_TYPE, false); _sendEmailMethod = null; MemberInfo[] search = null; if (_sendEmailMaint != null) { _sendEmailMethod = _sendEmailMaint.GetMethod(_SENDEMAIL_METHOD, BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public); search = _sendEmailMaint.GetMember(_SENDEMAILPARAMS_TYPE); } Type sendEmailParams = search != null && search.Length > 0 && search[0] is Type ? (Type)search[0] : null; if (sendEmailParams != null) { _sendEmailParamsCtor = sendEmailParams.GetConstructor(new Type[0]); _fromMethod = sendEmailParams.GetProperty("From"); _toMethod = sendEmailParams.GetProperty("To"); _ccMethod = sendEmailParams.GetProperty("Cc"); _bccMethod = sendEmailParams.GetProperty("Bcc"); _subjectMethod = sendEmailParams.GetProperty("Subject"); _bodyMethod = sendEmailParams.GetProperty("Body"); _activitySourceMethod = sendEmailParams.GetProperty("Source"); _parentSourceMethod = sendEmailParams.GetProperty("ParentSource"); _templateIDMethod = sendEmailParams.GetProperty("TemplateID"); _attachmentsMethod = sendEmailParams.GetProperty("Attachments"); } _canSendEmail = _sendEmailParamsCtor != null && _sendEmailMaint != null && _sendEmailMethod != null && _fromMethod != null && _toMethod != null && _ccMethod != null && _bccMethod != null && _subjectMethod != null && _bodyMethod != null && _activitySourceMethod != null && _parentSourceMethod != null && _templateIDMethod != null && _attachmentsMethod != null && !PXSiteMap.IsPortal; Type reportFunctionsType = System.Web.Compilation.BuildManager.GetType(_REPORTFUNCTIONS_TYPE, false); if (reportFunctionsType != null) ExpressionContext.RegisterExternalObject("Payments", Activator.CreateInstance(reportFunctionsType)); }
static Reports_RMLauncher() { _sendEmailMaint = System.Web.Compilation.BuildManager.GetType(_SENDEMAILMAINT_TYPE, false); _sendEmailMethod = null; MemberInfo[] search = null; if (_sendEmailMaint != null) { _sendEmailMethod = _sendEmailMaint.GetMethod(_SENDEMAIL_METHOD, BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public); search = _sendEmailMaint.GetMember(_SENDEMAILPARAMS_TYPE); } Type sendEmailParams = search != null && search.Length > 0 && search[0] is Type ? (Type)search[0] : null; if (sendEmailParams != null) { _sendEmailParamsCtor = sendEmailParams.GetConstructor(new Type[0]); _fromMethod = sendEmailParams.GetProperty("From"); _toMethod = sendEmailParams.GetProperty("To"); _ccMethod = sendEmailParams.GetProperty("Cc"); _bccMethod = sendEmailParams.GetProperty("Bcc"); _subjectMethod = sendEmailParams.GetProperty("Subject"); _bodyMethod = sendEmailParams.GetProperty("Body"); _activitySourceMethod = sendEmailParams.GetProperty("Source"); _parentSourceMethod = sendEmailParams.GetProperty("ParentSource"); _templateIDMethod = sendEmailParams.GetProperty("TemplateID"); _attachmentsMethod = sendEmailParams.GetProperty("Attachments"); } _canSendEmail = _sendEmailParamsCtor != null && _sendEmailMaint != null && _sendEmailMethod != null && _fromMethod != null && _toMethod != null && _ccMethod != null && _bccMethod != null && _subjectMethod != null && _bodyMethod != null && _activitySourceMethod != null && _parentSourceMethod != null && _templateIDMethod != null && _attachmentsMethod != null; }
public AssemblyLoaderImporter(ModuleReader moduleReader, AssemblyResolver assemblyResolver, EmbedTask embedTask) { instructionConstructorInfo = typeof (Instruction).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof (OpCode), typeof (object)}, null); this.moduleReader = moduleReader; this.assemblyResolver = assemblyResolver; this.embedTask = embedTask; }
public static bool ItGoodConstructor(ConstructorInfo C) { ParameterInfo[] ps = C.GetParameters(); var cs = from p in ps let prms = p.ParameterType.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) let pms = p.ParameterType.IsValueType where ((prms != null) || pms) select p; return (cs.Count() == ps.Length); }
public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) { 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]; 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(model, finalType, ref itemType, ref defaultType); Type tmp = itemType == null ? finalType : itemType; bool asReference = false; int typeIndex = model.FindOrAddAuto(tmp, false, true, false); if (typeIndex >= 0) { asReference = model[tmp].AsReferenceDefault; } IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, false, false, true), serializer; if (tail == null) { throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); } tail = new TagDecorator(i + 1, wireType, false, tail); if (itemType == null) { serializer = tail; } else { if (finalType.IsArray) { serializer = new ArrayDecorator(model, tail, i + 1, false, wireType, finalType, false, false); } else { serializer = ListDecorator.Create(model, finalType, defaultType, tail, i + 1, false, wireType, true, false, false); } } tails[i] = serializer; } }
public static StringBuilder BuildConstructors(Type type, ConstructorInfo[] constructors, int slot, int howmanyConstructors) { string fmt = @" _jstype.definition.{0} = function({1}) [[ CS.Call({2}); ]]"; StringBuilder sb = new StringBuilder(); var argActual = new cg.args(); var argFormal = new cg.args(); for (int i = 0; i < constructors.Length; i++) { ConstructorInfo con = constructors[i]; ParameterInfo[] ps = con == null? new ParameterInfo[0] : con.GetParameters(); argActual.Clear().Add( (int)JSVCall.Oper.CONSTRUCTOR, // OP slot, i, // NOTICE "true", // IsStatics "this" ); argFormal.Clear(); // add T to formal param if (type.IsGenericTypeDefinition) { // TODO check int TCount = type.GetGenericArguments().Length; for (int j = 0; j < TCount; j++) { argFormal.Add("t" + j + ""); argActual.Add("t" + j + ".getNativeType()"); } } //StringBuilder sbFormalParam = new StringBuilder(); //StringBuilder sbActualParam = new StringBuilder(); for (int j = 0; j < ps.Length; j++) { argFormal.Add("a" + j.ToString()); argActual.Add("a" + j.ToString()); } sb.AppendFormat(fmt, SharpKitMethodName("ctor", ps, howmanyConstructors > 1), // [0] argFormal, // [1] argActual); // [2] } return sb; }
public static object ObjectFromConstructor(ConstructorInfo C) { ParameterInfo[] ps = C.GetParameters(); List<object> o = new List<object>(); for (int i = 0; i < ps.Length; i++) { // if (ps[i].DefaultValue != null) o.Add(ps[i].DefaultValue); else if (ps[i].ParameterType.IsValueType) o.Add(Activator.CreateInstance(ps[i].ParameterType)); else o.Add(ps[i].ParameterType.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null).Invoke(null)); } return C.Invoke(o.ToArray()); }
public static void InitType() { if (realType == null) { Assembly assembly = Assembly.GetAssembly(typeof(Editor)); realType = assembly.GetType("UnityEditor.AvatarPreview"); method_ctor = realType.GetConstructor(new Type[] { typeof(Animator), typeof(Motion)}); property_OnAvatarChangeFunc = realType.GetProperty("OnAvatarChangeFunc"); property_IKOnFeet = realType.GetProperty("IKOnFeet"); property_Animator = realType.GetProperty("Animator"); method_DoPreviewSettings = realType.GetMethod("DoPreviewSettings"); method_OnDestroy = realType.GetMethod("OnDestroy"); method_DoAvatarPreview = realType.GetMethod("DoAvatarPreview", new Type[] {typeof(Rect), typeof(GUIStyle)}); method_ResetPreviewInstance = realType.GetMethod("ResetPreviewInstance"); // method_CalculatePreviewGameObject = realType.GetMethod("CalculatePreviewGameObject", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); field_timeControl = realType.GetField("timeControl"); } }
/// <summary> /// Construct an instance of the given target rules /// </summary> /// <param name="TypeName">Type name of the target rules</param> /// <param name="TargetInfo">Target configuration information to pass to the constructor</param> /// <returns>Instance of the corresponding TargetRules</returns> protected TargetRules CreateTargetRulesInstance(string TypeName, TargetInfo TargetInfo) { // The build module must define a type named '<TargetName>Target' that derives from our 'TargetRules' type. Type RulesType = CompiledAssembly.GetType(TypeName); if (RulesType == null) { throw new BuildException("Expecting to find a type to be declared in a target rules named '{0}'. This type must derive from the 'TargetRules' type defined by Unreal Build Tool.", TypeName); } // Create an instance of the module's rules object, and set some defaults before calling the constructor. TargetRules Rules = (TargetRules)FormatterServices.GetUninitializedObject(RulesType); Rules.bUseBackwardsCompatibleDefaults = bUseBackwardsCompatibleDefaults; // Find the constructor ConstructorInfo Constructor = RulesType.GetConstructor(new Type[] { typeof(TargetInfo) }); if (Constructor == null) { throw new BuildException("No constructor found on {0} which takes an argument of type TargetInfo.", RulesType.Name); } // Invoke the regular constructor try { Constructor.Invoke(Rules, new object[] { TargetInfo }); } catch (Exception Ex) { throw new BuildException(Ex, "Unable to instantiate instance of '{0}' object type from compiled assembly '{1}'. Unreal Build Tool creates an instance of your module's 'Rules' object in order to find out about your module's requirements. The CLR exception details may provide more information: {2}", TypeName, Path.GetFileNameWithoutExtension(CompiledAssembly.Location), Ex.ToString()); } Rules.SetOverridesForTargetType(); return(Rules); }
private object CreateInstanceWithCtor(Type type, object[] args) { ConstructorInfo ctor = null; if (args == null || args.Length == 0) { ctor = type.GetConstructor(BF_AllInstanceMembers, null, Type.EmptyTypes, null); } if (ctor == null) { // We go down this path even if there are no args, because we might match a params array ConstructorInfo[] ctors = type.GetConstructors(BF_AllInstanceMembers); // This method throws if it can't find a match, so ctor will never be null ctor = (ConstructorInfo)BindToMethod(BF_AllInstanceMembers, ctors, args); } FactoryDelegate factoryDelegate; if (!FactoryDelegates.TryGetValue(ctor, out factoryDelegate)) { factoryDelegate = CreateFactoryDelegate(ctor); FactoryDelegates.Add(ctor, factoryDelegate); } return(factoryDelegate.Invoke(args)); }
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 static void RegisterDefault <T>() where T : CompilerBase <CSharpCompilation, CSharpCompilationOptions>, new() { #if DEBUG Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); #endif DynamicMethod method = new DynamicMethod("Compilation" + Guid.NewGuid().ToString(), typeof(T), new Type[0]); ILGenerator il = method.GetILGenerator(); ConstructorInfo ctor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Ret); GetCompiler = (Func <T>)(method.CreateDelegate(typeof(Func <T>))); var compilerHandler = GetCompiler(); var option = compilerHandler.GetCompilationOptions(); var compiler = compilerHandler.GetCompilation(option); //var tree = CSharpSyntaxTree.ParseText("using System; public class natashaCompilerTest{}"); //compiler = compiler.AddSyntaxTrees(tree); //var semantiModel = compiler.GetSemanticModel(tree); #if DEBUG stopwatch.StopAndShowCategoreInfo("[Compiler]", "编译器初始化", 1); #endif }
public object CreateInstance(Type type) { Type instanceType = this[type] ?? type; if (instanceType.IsInterface || instanceType.IsAbstract) { throw new InvalidOperationException($"Type {instanceType.FullName} cannot be instantiated."); } ConstructorInfo constructor = instanceType .GetConstructors() .OrderBy(x => x.GetParameters().Length) .First(); ParameterInfo[] constructorParameters = constructor.GetParameters(); object[] constructorParameterObjects = new object[constructorParameters.Length]; for (int i = 0; i < constructorParameters.Length; i++) { constructorParameterObjects[i] = this.CreateInstance(constructorParameters[i].ParameterType); } return(constructor.Invoke(constructorParameterObjects)); }
/// <summary> /// Initialize the argument property. /// </summary> /// <param name="constructorInfo"></param> /// <param name="configScope"></param> public void Initialize(ConfigurationScope configScope, ConstructorInfo constructorInfo) { // Search argument by his name to set his type ParameterInfo[] parameters = constructorInfo.GetParameters(); bool found = false; for (int i = 0; i < parameters.Length; i++) { found = (parameters[i].Name == _argumentName); if (found) { _argumentType = parameters[i].ParameterType; break; } } if (this.CallBackName != null && this.CallBackName.Length > 0) { configScope.ErrorContext.MoreInfo = "Argument property (" + _argumentName + "), check the typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation)."; try { Type type = configScope.SqlMapper.TypeHandlerFactory.GetType(this.CallBackName); ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback)Activator.CreateInstance(type); this.TypeHandler = new CustomTypeHandler(typeHandlerCallback); } catch (Exception e) { throw new CommonExceptions.ConfigurationException("Error occurred during custom type handler configuration. Cause: " + e.Message, e); } } else { configScope.ErrorContext.MoreInfo = "Argument property (" + _argumentName + ") set the typeHandler attribute."; this.TypeHandler = this.ResolveTypeHandler(configScope, _argumentType, this.CLRType, this.DbType); } }
private FieldBuilder GenerateTypedSerializers(Dictionary <string, string> serializers, TypeBuilder serializerContractTypeBuilder) { string privateName = "typedSerializers"; FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder); MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } ); foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty <Type>() ); ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); } GenerateHashtableGetEnd(fieldBuilder); return(fieldBuilder); }
static SpringASTFactory() { BASENODE_TYPE = typeof(SpringAST); Typename2Creator = new Hashtable(); foreach (Type type in typeof(SpringASTFactory).Assembly.GetTypes()) { if (BASENODE_TYPE.IsAssignableFrom(type)) { if (type.IsAbstract || type.IsInterface) { continue; } ConstructorInfo ctor = type.GetConstructor(new Type[0]); if (ctor != null) { ASTNodeCreator creator = new ASTNodeCreator(ctor); Typename2Creator[creator.ASTNodeTypeName] = creator; } } } Typename2Creator[BASENODE_TYPE.FullName] = SpringAST.Creator; }
static void Main(string[] args) { var dirs = Directory.GetFiles(@"..\..\..\..\AppDomainDLL\AllDll", "*.dll"); for (int i = 0; i < dirs.Length; i++) { Assembly assembly = Assembly.Load(AssemblyName.GetAssemblyName(dirs[i])); Type type = assembly.GetType($"ClassLibrary{i + 1}.Class{i + 1}"); Console.WriteLine("Название DLL: " + type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); var MyClass = constructor.Invoke(null); //Console.WriteLine(type.GetInterface("IExtension")); var res = type.GetInterface("IExtension"); if (res != null) { MethodInfo method = type.GetMethod("GetExtensionName"); Console.WriteLine("Содержимое DLL: " + (string)method.Invoke(MyClass, null) + "\n"); } else { Console.WriteLine("Нет реализации \"IExtension\" интерфейса\n"); } } }
private static void GetConstructor(string pageKey, object parameter, out ConstructorInfo constructor, out object[] parameters) { Type type = PagesByKey[pageKey]; if (parameter == null) { constructor = type.GetTypeInfo() .DeclaredConstructors .FirstOrDefault(c => !c.GetParameters().Any()); parameters = new object[] { }; } else { constructor = type.GetTypeInfo() .DeclaredConstructors .FirstOrDefault( c => { ParameterInfo[] p = c.GetParameters(); return(p.Count() == 1 && p[0].ParameterType == parameter.GetType()); }); parameters = new[] { parameter }; } if (constructor == null) { throw new InvalidOperationException($"No suitable constructor found for page {pageKey}"); } }
private static object GenerateComplexObject(Type type, Dictionary <Type, object> createdObjectReferences) { if (createdObjectReferences.TryGetValue(type, out object result)) { return(result); // The object has been created already, just return it. This will handle the circular reference case. } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { return(null); // Cannot instantiate the type because it does not have a default constructor } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return(result); }
//do not remove this is referenced through GetActivatorMethod private static ObjectActivator <T> GetActivator <T>(ConstructorInfo ctor) { var paramsInfo = ctor.GetParameters(); //create a single param of type object[] var param = Expression.Parameter(typeof(object[]), "args"); var argsExp = new Expression[paramsInfo.Length]; //pick each arg from the params array //and create a typed expression of them for (var i = 0; i < paramsInfo.Length; i++) { var index = Expression.Constant(i); var paramType = paramsInfo[i].ParameterType; var paramAccessorExp = Expression.ArrayIndex(param, index); var paramCastExp = Expression.Convert(paramAccessorExp, paramType); argsExp[i] = paramCastExp; } //make a NewExpression that calls the //ctor with the args we just created var newExp = Expression.New(ctor, argsExp); //create a lambda with the New //Expression as body and our param object[] as arg var lambda = Expression.Lambda(typeof(ObjectActivator <T>), newExp, param); //compile it var compiled = (ObjectActivator <T>)lambda.Compile(); return(compiled); }
public void onResult(AndroidJavaObject arg_Result_1) { IntPtr rawObject = arg_Result_1.GetRawObject(); ConstructorInfo constructor = typeof(R).GetConstructor(new Type[1] { rawObject.GetType() }); R val; if (constructor != null) { val = (R)constructor.Invoke(new object[1] { rawObject }); } else { ConstructorInfo constructor2 = typeof(R).GetConstructor(new Type[0]); val = (R)constructor2.Invoke(new object[0]); Marshal.PtrToStructure(rawObject, val); } OnResult(val); }
private static bool TryGetIniters(Type instType, Type loaderType, Type[] parmTypes, out MethodInfo getter, out ConstructorInfo ctor, out MethodInfo create, out bool requireEnvironment) { getter = null; ctor = null; create = null; requireEnvironment = false; var parmTypesWithEnv = Utils.Concat(new Type[1] { typeof(IHostEnvironment) }, parmTypes); if (Utils.Size(parmTypes) == 0 && (getter = FindInstanceGetter(instType, loaderType)) != null) { return(true); } if (instType.IsAssignableFrom(loaderType) && (ctor = loaderType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parmTypes ?? Type.EmptyTypes, null)) != null) { return(true); } if (instType.IsAssignableFrom(loaderType) && (ctor = loaderType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parmTypesWithEnv ?? Type.EmptyTypes, null)) != null) { requireEnvironment = true; return(true); } if ((create = FindCreateMethod(instType, loaderType, parmTypes ?? Type.EmptyTypes)) != null) { return(true); } if ((create = FindCreateMethod(instType, loaderType, parmTypesWithEnv ?? Type.EmptyTypes)) != null) { requireEnvironment = true; return(true); } return(false); }
/// <devdoc> /// Helper method to safely invoke a .ctor. You should prefer SecureCreateInstance to this. /// Set allowNonPublic to true if you want non public ctors to be used. /// The 'extraFlags' parameter is used to pass in any other flags you need, /// besides Public, NonPublic and Instance. /// </devdoc> internal static object SecureConstructorInvoke(Type type, Type[] argTypes, object[] args, bool allowNonPublic, BindingFlags extraFlags) { if (type == null) { throw new ArgumentNullException("type"); } // if it's an internal type, we demand reflection permission. if (!type.IsVisible) { DemandReflectionAccess(type); } else if (allowNonPublic && !HasReflectionPermission(type)) { // Someone is trying to invoke a ctor on a public type, but does not // have full reflection permission. We shouldn't pass BindingFlags.NonPublic in this case. allowNonPublic = false; } BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | extraFlags; if (!allowNonPublic) { flags &= ~BindingFlags.NonPublic; } ConstructorInfo ctor = type.GetConstructor(flags, null, argTypes, null); if (ctor != null) { return(ctor.Invoke(args)); } return(null); }
public static List <IBeingInterface> AddBeing(byte[] dll) { List <IBeingInterface> objects = new List <IBeingInterface>(); Assembly assembly = Assembly.Load(dll); string iMyInterfaceName = typeof(IBeingInterface).ToString(); TypeDelegator[] defaultConstructorParametersTypes = new TypeDelegator[0]; object[] defaultConstructorParameters = new object[0]; IBeingInterface iAI = null; foreach (Type type in assembly.GetTypes()) { if (type.GetInterface(iMyInterfaceName) != null) { ConstructorInfo defaultConstructor = type.GetConstructor(defaultConstructorParametersTypes); object instance = defaultConstructor.Invoke(defaultConstructorParameters); iAI = (IBeingInterface)instance; //Достаём таки нужный интерфейс // objects.Add(iAI); } } return(objects); }
public void Invoke_SZArrayConstructor() { Type type = Type.GetType("System.Object[]"); ConstructorInfo[] constructors = TypeExtensions.GetConstructors(type); Assert.Equal(1, constructors.Length); ConstructorInfo constructor = constructors[0]; int[] blength = new int[] { -100, -9, -1 }; for (int j = 0; j < blength.Length; j++) { Assert.Throws <OverflowException>(() => constructor.Invoke(new object[] { blength[j] })); } int[] glength = new int[] { 0, 1, 2, 3, 5, 10, 99, 65535 }; for (int j = 0; j < glength.Length; j++) { object[] arr = (object[])constructor.Invoke(new object[] { glength[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength[j], arr.Length); } }
private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator) { if (type.IsValueType()) { generator.DeclareLocal(type); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Box, type); } else { ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) { throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); } generator.Emit(OpCodes.Newobj, constructorInfo); } generator.Return(); }
private object ReflectionCreateCollection(CollectionDataContract collectionContract) { if (IsArrayLikeCollection(collectionContract)) { Type arrayType = collectionContract.ItemType.MakeArrayType(); var ci = arrayType.GetConstructor(s_arrayConstructorParameters) !; var newArray = ci.Invoke(s_arrayConstructorArguments); return(newArray); } else if (collectionContract.Kind == CollectionKind.GenericDictionary && collectionContract.UnderlyingType.IsInterface) { Type type = Globals.TypeOfDictionaryGeneric.MakeGenericType(collectionContract.ItemType.GetGenericArguments()); ConstructorInfo ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes) !; object newGenericDict = ci.Invoke(Array.Empty <object>()); return(newGenericDict); } else { if (collectionContract.UnderlyingType.IsValueType) { object newValueObject = Activator.CreateInstance(collectionContract.UnderlyingType) !; return(newValueObject); } else if (collectionContract.UnderlyingType == Globals.TypeOfIDictionary) { object newGenericDict = new Dictionary <object, object>(); return(newGenericDict); } else { ConstructorInfo ci = collectionContract.Constructor !; object newCollection = ci.Invoke(Array.Empty <object>()); return(newCollection); } } }
private static MetaConstructor CreateConstructorDelegate(Type iCICType) { ConstructorInfo cInfo = null; if (iCICType.GetInterface(typeof(ICaisisInputControl).FullName) != null && !iCICType.IsInterface) { cInfo = iCICType.GetConstructor(new Type[] { }); } if (cInfo != null) { DynamicMethod creator = new DynamicMethod( String.Concat("_Creator", cInfo.DeclaringType.Name, "_"), typeof(ICaisisInputControl) , new Type[] { }, cInfo.DeclaringType); ILGenerator generator = creator.GetILGenerator(); generator.Emit(OpCodes.Newobj, cInfo); generator.Emit(OpCodes.Ret); MetaConstructor metaC = creator.CreateDelegate(typeof(MetaConstructor)) as MetaConstructor; return(metaC); } else { return(null); } }
private int GetConstructorSignatureInternal(LuaState luaState) { ProxyType klass = null; int udata = luaState.CheckUObject(1, "luaNet_class"); if (udata != -1) { klass = (ProxyType)_objects[udata]; } if (klass == null) { ThrowError(luaState, "get_constructor_bysig: first arg is invalid type reference"); return(1); } var signature = new Type[luaState.GetTop() - 1]; for (int i = 0; i < signature.Length; i++) { signature[i] = FindType(luaState.ToString(i + 2, false)); } try { ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor(signature); var wrapper = new LuaMethodWrapper(this, null, klass, constructor); var invokeDelegate = wrapper.InvokeFunction; PushFunction(luaState, invokeDelegate); } catch (Exception e) { ThrowError(luaState, e); } return(1); }
internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper <>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List <>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { constructorArgument = typeof(ICollection <>).MakeGenericType(CollectionItemType); } else { constructorArgument = _genericCollectionDefinitionType; } ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return((IWrappedCollection)_genericWrapperCreator(list)); }
/// <summary> /// Method to create the data endpoint /// </summary> /// <param name="logger">The logger to use</param> /// <param name="globalMeta">Global meta dictionary</param> /// <param name="meta">Meta dictionary</param> /// <returns>The data endpoint</returns> public override IDataEndpoint Create(Logger logger, MetaDictionary meta, MetaDictionary globalMeta) { IDataEndpoint server = null; ConstructorInfo ci = _type.GetConstructor(new [] { typeof(Logger) }); if (ci != null) { server = (IDataEndpoint)ci.Invoke(new [] { logger }); } else { ci = _type.GetConstructor(new Type[0]); if (ci == null) { throw new NetServiceException("Can not find an appropriate constructor for endpoint"); } server = (IDataEndpoint)ci.Invoke(new object[0]); } server.Meta = meta; server.GlobalMeta = globalMeta; if (Config != null) { IPersistNode persist = server as IPersistNode; if (persist != null) { persist.SetState(Config, logger); } } return(server); }
public static void SendCtor(Type type, ConstructorInfo ctor, Mobile from) { ParameterInfo[] paramList = ctor.GetParameters(); StringBuilder sb = new StringBuilder(); sb.Append(type.Name); for (int i = 0; i < paramList.Length; ++i) { if (i != 0) { sb.Append(','); } sb.Append(' '); sb.Append(paramList[i].ParameterType.Name); sb.Append(' '); sb.Append(paramList[i].Name); } from.SendMessage(sb.ToString()); }
/// <summary> /// Build the StructureField attribute for a complex type. /// </summary> public static void StructureFieldAttribute( this PropertyBuilder typeBuilder, StructureField structureField) { var attributeType = typeof(StructureFieldAttribute); ConstructorInfo ctorInfo = attributeType.GetConstructor(Type.EmptyTypes); CustomAttributeBuilder builder = new CustomAttributeBuilder( ctorInfo, new object[0], // constructor arguments new[] // properties to assign { attributeType.GetProperty("ValueRank"), attributeType.GetProperty("MaxStringLength"), attributeType.GetProperty("IsOptional") }, new object[] // values to assign { structureField.ValueRank, structureField.MaxStringLength, structureField.IsOptional }); typeBuilder.SetCustomAttribute(builder); }
object IConvertible.ToType(Type conversionType, IFormatProvider provider) { if (conversionType == null) { throw new ArgumentNullException("conversionType"); } Type thisType = this.GetType(); if (thisType == conversionType) { // no conversion needed return this; } if (!conversionType.IsGenericType || typeof(Rational<>) != conversionType.GetGenericTypeDefinition()) { // fall back to basic conversion return Convert.ChangeType(this, conversionType, provider); } // auto-convert between Rational<T> types by converting Numerator/Denominator Type genericArg = conversionType.GetGenericArguments()[0]; object[] ctorArgs = { Convert.ChangeType(this.Numerator, genericArg, provider), Convert.ChangeType(this.Denominator, genericArg, provider) }; ConstructorInfo ctor = conversionType.GetConstructor(new Type[] { genericArg, genericArg }); if (ctor == null) { throw new InvalidCastException("Unable to find constructor for Rational<"+genericArg.Name+">."); } return ctor.Invoke(ctorArgs); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == (Type)null) { throw new ArgumentNullException("destinationType"); } if (value is Color) { Color color = (Color)value; if (destinationType == typeof(string)) { return((object)BaseConverter.ConvertFromValues <byte>(context, culture, color.ToArray())); } if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo constructor = typeof(Color).GetConstructor(MathUtil.Array <Type>(typeof(byte), 4)); if (constructor != (ConstructorInfo)null) { return((object)new InstanceDescriptor((MemberInfo)constructor, (ICollection)color.ToArray())); } } } return(base.ConvertTo(context, culture, value, destinationType)); }
private static void LoadPlugin(Assembly assembly) { foreach (Type type in assembly.ExportedTypes) { if (!type.IsSubclassOf(typeof(Plugin))) { continue; } if (type.IsAbstract) { continue; } ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); try { constructor?.Invoke(null); } catch (Exception ex) { Utility.Log(nameof(Plugin), LogLevel.Error, ex); } } }
/// <summary> /// 获取强类型的实例 /// </summary> /// <param name="type"></param> /// <returns></returns> public static object GetInstance(Type type) { if (_hTable.ContainsKey(type.FullName)) { //返回已有实例 return(_hTable[type.FullName]); } else { //构造唯一实例 ConstructorInfo[] infos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); ConstructorInfo constructorInfo = null; foreach (ConstructorInfo info in infos) { if (info.GetParameters().Length == 0) { constructorInfo = info; break; } } if (constructorInfo == null) { ErrorRecord.Record(" NotSupportedException 没有无参构造函数 type.FullName:" + type.FullName); throw new NotSupportedException("没有无参构造函数"); } object instance = constructorInfo.Invoke(null); lock (SyncRoot) { _hTable.Add(type.FullName, instance); } return(instance); } }
public void CallNutritionApi(string NDBNo, int ProductID) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://api.nal.usda.gov/ndb/reports/?format=json&type=b&api_key=HBS3lRZUgBIxXOSF1DQBKW7GJw6M6e2J4cFMzSSP&ndbno=" + NDBNo + ""); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(client.BaseAddress).Result; if (response.IsSuccessStatusCode) { var dataObject = response.Content.ReadAsAsync <rootObject>().Result; foreach (nutrients nutrient in dataObject.report.food.nutrients) { int TblPrimaryKey = 0; object objNT = DB.ExecuteScalar("select va019_nutrition_id from va019_nutrition where m_product_id=" + ProductID + " and va019_nutrition_key=" + nutrient.nutrient_id + ""); if (objNT != null && objNT != DBNull.Value) { TblPrimaryKey = Convert.ToInt32(objNT); } var Dll = Assembly.Load("VA019Svc"); var X_VA019_Nutrition = Dll.GetType("ViennaAdvantage.Model.MVA019Nutrition"); ConstructorInfo conInfo = X_VA019_Nutrition.GetConstructor(new[] { typeof(Ctx), typeof(int), typeof(Trx), typeof(int), typeof(string), typeof(int), typeof(string), typeof(decimal) }); conInfo.Invoke(new object[] { p_ctx, TblPrimaryKey, null, ProductID, nutrient.name, nutrient.nutrient_id, nutrient.unit, nutrient.value }); } } else { log.SaveError("Nutretion API Response Falier", ""); } } catch (Exception e) { log.SaveError("Nutretion API Error", e); } }
internal CustomClassLoaderCtorCaller(ConstructorInfo ctor, object classLoader, Assembly assembly) { this.ctor = ctor; this.classLoader = classLoader; this.assembly = assembly; }
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); }
void Initialize(Type targetType, string methodName) { if (!_delegateType.IsSubclassOf(_typeMapper.MapType(typeof(Delegate)))) throw new ArgumentException(Properties.Messages.ErrInvalidDelegateType, "delegateType"); IMemberInfo delegateInvocationMethod = null; foreach (IMemberInfo mi in _typeMapper.TypeInfo.GetMethods(_delegateType)) { if (mi.Name == "Invoke") { if (delegateInvocationMethod != null) throw new ArgumentException(Properties.Messages.ErrInvalidDelegateType, "delegateType"); delegateInvocationMethod = mi; } } if (delegateInvocationMethod == null) throw new ArgumentException(Properties.Messages.ErrInvalidDelegateType, "delegateType"); foreach (IMemberInfo mi in _typeMapper.TypeInfo.GetConstructors(_delegateType)) { if (mi.IsStatic) continue; Type[] ctorParamTypes = mi.ParameterTypes; if (ctorParamTypes.Length == 2 && ctorParamTypes[0] == _typeMapper.MapType(typeof(object)) && ctorParamTypes[1] == _typeMapper.MapType(typeof(IntPtr))) { if (_delegateConstructor != null) throw new ArgumentException(Properties.Messages.ErrInvalidDelegateType, "delegateType"); _delegateConstructor = (ConstructorInfo)mi.Member; } } if (_delegateConstructor == null) throw new ArgumentException(Properties.Messages.ErrInvalidDelegateType, "delegateType"); Type retType = delegateInvocationMethod.ReturnType; Type[] parameterTypes = delegateInvocationMethod.ParameterTypes; for ( ; targetType != null; targetType = targetType.BaseType) { foreach (IMemberInfo mi in _typeMapper.TypeInfo.Filter(_typeMapper.TypeInfo.GetMethods(targetType), methodName, false, (object)_target == null, false)) { if (mi.ReturnType == retType && ArrayUtils.Equals(mi.ParameterTypes, parameterTypes)) { if (_method == null) _method = (MethodInfo)mi.Member; else throw new AmbiguousMatchException(Properties.Messages.ErrAmbiguousBinding); } } if (_method != null) break; } if (_method == null) throw new MissingMethodException(Properties.Messages.ErrMissingMethod); }
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { methodBuilder.SetCustomAttribute(con, binaryAttribute); }
internal SmartConstructorMethodWrapper(TypeWrapper declaringType, string name, string sig, ConstructorInfo method, TypeWrapper[] parameterTypes, Modifiers modifiers, MemberFlags flags) : base(declaringType, name, sig, method, PrimitiveTypeWrapper.VOID, parameterTypes, modifiers, flags) { }
private static ConstructorInfo AddConstructor(TypeBuilder tb, MethodWrapper defaultConstructor, ConstructorInfo serializationConstructor, bool callReadObject) { ConstructorBuilder ctor = tb.DefineConstructor(MethodAttributes.Family, CallingConventions.Standard, new Type[] { JVM.Import(typeof(SerializationInfo)), JVM.Import(typeof(StreamingContext)) }); AttributeHelper.HideFromJava(ctor); ctor.AddDeclarativeSecurity(SecurityAction.Demand, psetSerializationFormatter); CodeEmitter ilgen = CodeEmitter.Create(ctor); ilgen.Emit(OpCodes.Ldarg_0); if (defaultConstructor != null) { defaultConstructor.EmitCall(ilgen); } else { ilgen.Emit(OpCodes.Ldarg_1); ilgen.Emit(OpCodes.Ldarg_2); ilgen.Emit(OpCodes.Call, serializationConstructor); } if (callReadObject) { ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldarg_1); TypeWrapper serializationHelper = ClassLoaderWrapper.LoadClassCritical("ikvm.internal.Serialization"); MethodWrapper mw = serializationHelper.GetMethodWrapper("readObject", "(Ljava.lang.Object;Lcli.System.Runtime.Serialization.SerializationInfo;)V", false); mw.Link(); mw.EmitCall(ilgen); } ilgen.Emit(OpCodes.Ret); return ctor; }
public static StringBuilder BuildConstructors(Type type, ConstructorInfo[] constructors, int[] constructorsIndex, ClassCallbackNames ccbn) { /* * methods * 0 function name * 1 list<CSParam> generation * 2 function call */ string fmt = @" static bool {0}(JSVCall vc, int argc) [[ {1} return true; ]] "; StringBuilder sb = new StringBuilder(); /*if (constructors.Length == 0 && JSBindingSettings.IsGeneratedDefaultConstructor(type) && (type.IsValueType || (type.IsClass && !type.IsAbstract && !type.IsInterface))) { int olIndex = 1; bool returnVoid = false; string functionName = type.Name + "_" + type.Name + (olIndex > 0 ? olIndex.ToString() : "") + "";// (cons.IsStatic ? "_S" : ""); sb.AppendFormat(fmt, functionName, BuildNormalFunctionCall(0, new ParameterInfo[0], type.Name, type.Name, false, returnVoid, null, true)); ccbn.constructors.Add(functionName); ccbn.constructorsCSParam.Add(GenListCSParam2(new ParameterInfo[0]).ToString()); }*/ // increase index if adding default constructor // int deltaIndex = 0; if (JSBindingSettings.NeedGenDefaultConstructor(type)) { // deltaIndex = 1; } for (int i = 0; i < constructors.Length; i++) { ConstructorInfo cons = constructors[i]; if (cons == null) { sb.AppendFormat("public static ConstructorID constructorID{0} = new ConstructorID({1});\n", i, "null, null"); // this is default constructor //bool returnVoid = false; //string functionName = type.Name + "_" + type.Name + "1"; int olIndex = i + 1; // for constuctors, they are always overloaded string functionName = JSNameMgr.HandleFunctionName(type.Name + "_" + type.Name + (olIndex > 0 ? olIndex.ToString() : "")); sb.AppendFormat(fmt, functionName, BuildNormalFunctionCall(0, new ParameterInfo[0], type.Name, false, null, true)); ccbn.constructors.Add(functionName); ccbn.constructorsCSParam.Add(GenListCSParam2(new ParameterInfo[0]).ToString()); } else { ParameterInfo[] paramS = cons.GetParameters(); int olIndex = i + 1; // for constuctors, they are always overloaded int methodTag = i/* + deltaIndex*/; for (int j = 0; j < paramS.Length; j++) { if (JSDataExchangeEditor.IsDelegateDerived(paramS[j].ParameterType)) { StringBuilder sbD = JSDataExchangeEditor.Build_DelegateFunction(type, cons, paramS[j].ParameterType, methodTag, j); sb.Append(sbD); } } // ConstructorID if (type.IsGenericTypeDefinition) { cg.args arg = new cg.args(); cg.args arg1 = new cg.args(); cg.args arg2 = new cg.args(); foreach (ParameterInfo p in cons.GetParameters()) { cg.args argFlag = ParameterInfo2TypeFlag(p); arg1.AddFormat("\"{0}\"", p.ParameterType.Name); arg2.Add(argFlag.Format(cg.args.ArgsFormat.Flag)); } if (arg1.Count > 0) arg.AddFormat("new string[]{0}", arg1.Format(cg.args.ArgsFormat.Brace)); else arg.Add("null"); if (arg2.Count > 0) arg.AddFormat("new TypeFlag[]{0}", arg2.Format(cg.args.ArgsFormat.Brace)); else arg.Add("null"); sb.AppendFormat("public static ConstructorID constructorID{0} = new ConstructorID({1});\n", i, arg.ToString()); } string functionName = JSNameMgr.HandleFunctionName(type.Name + "_" + type.Name + (olIndex > 0 ? olIndex.ToString() : "") + (cons.IsStatic ? "_S" : "")); sb.AppendFormat(fmt, functionName, BuildNormalFunctionCall(methodTag, paramS, cons.Name, cons.IsStatic, null, true, 0)); ccbn.constructors.Add(functionName); ccbn.constructorsCSParam.Add(GenListCSParam2(paramS).ToString()); } } return sb; }
static ConstructorInfo [] GetAllConstructors (Type t) { BindingFlags static_flag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly |BindingFlags.Static; BindingFlags instance_flag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly |BindingFlags.Instance; ConstructorInfo [] static_members = t.GetConstructors (static_flag); ConstructorInfo [] instance_members = t.GetConstructors (instance_flag); if (static_members == null && instance_members == null) return null; ConstructorInfo [] all_members = new ConstructorInfo [static_members.Length + instance_members.Length]; static_members.CopyTo (all_members, 0); // copy all static members instance_members.CopyTo (all_members, static_members.Length); // copy all instance members return all_members; }
static void ConstructorGen (ConstructorInfo c, Type t) { ParameterInfo[] parameters = c.GetParameters (); FunctionGen (parameters, (MethodBase) c, t, null, true); }
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { try { type.StartSync(); type.module.assembly.SetCustomAttribute (this, con, binaryAttribute); } finally { type.EndSync(); } }
public virtual void Emit (OpCode opcode, ConstructorInfo con) { int token = token_gen.GetToken (con, true); make_room (6); ll_emit (opcode); if (con.DeclaringType.Module == module) add_token_fixup (con); emit_int (token); if (opcode.StackBehaviourPop == StackBehaviour.Varpop) cur_stack -= con.GetParametersCount (); }
public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); }
internal void Emit(OpCode opcode, ConstructorInfo con) { EmitOpCode(opcode, con); }
public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor) { return new ConstructorInfoImpl(GetMethod(type, constructor.GetMethodInfo())); }
internal static void GetConstructors(Type type, out ConstructorInfo defCtor, out ConstructorInfo singleOneArgCtor) { defCtor = null; int oneArgCtorCount = 0; ConstructorInfo oneArgCtor = null; ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); // HACK we have a special rule to make some additional custom attributes from mscorlib usable: // Attributes that have two constructors, one an enum and another one taking a byte, short or int, // we only expose the enum constructor. if (constructors.Length == 2 && type.Assembly == Types.Object.Assembly) { ParameterInfo[] p0 = constructors[0].GetParameters(); ParameterInfo[] p1 = constructors[1].GetParameters(); if (p0.Length == 1 && p1.Length == 1) { Type t0 = p0[0].ParameterType; Type t1 = p1[0].ParameterType; bool swapped = false; if (t1.IsEnum) { Type tmp = t0; t0 = t1; t1 = tmp; swapped = true; } if (t0.IsEnum && (t1 == Types.Byte || t1 == Types.Int16 || t1 == Types.Int32)) { if (swapped) { singleOneArgCtor = constructors[1]; } else { singleOneArgCtor = constructors[0]; } return; } } } if (type.Assembly == Types.Object.Assembly) { if (type.FullName == "System.Runtime.CompilerServices.MethodImplAttribute") { foreach (ConstructorInfo ci in constructors) { ParameterInfo[] p = ci.GetParameters(); if (p.Length == 1 && p[0].ParameterType.IsEnum) { singleOneArgCtor = ci; return; } } } } foreach (ConstructorInfo ci in constructors) { ParameterInfo[] args = ci.GetParameters(); if (args.Length == 0) { defCtor = ci; } else if (args.Length == 1) { if (IsSupportedType(args[0].ParameterType)) { oneArgCtor = ci; oneArgCtorCount++; } else { // set to two to make sure we don't see the oneArgCtor as viable oneArgCtorCount = 2; } } } singleOneArgCtor = oneArgCtorCount == 1 ? oneArgCtor : null; }
static string AddConstructorSignature (ConstructorInfo constructor) { string signature; string visibility = GetMethodVisibility (constructor); if (visibility == null) return null; string modifiers = GetMethodModifiers (constructor); string name = constructor.DeclaringType.Name; string parameters = GetMethodParameters (constructor); signature = String.Format ("{0}{1} {2} {3};", visibility, modifiers, name, parameters); return signature; }
static bool HasMissingType (ConstructorInfo ctor) { #if STATIC // // Mimic odd csc behaviour where missing type on predefined // attributes means the attribute is silently ignored. This can // happen with PCL facades // foreach (var p in ctor.GetParameters ()) { if (p.ParameterType.__ContainsMissingType) return true; } #endif return false; }
static void AddConstructor (XmlElement members, ConstructorInfo constructor) { XmlDocument document = members.OwnerDocument; string signature = AddConstructorSignature (constructor); string constructor_name = constructor.Name; // .cctors are not suppose to be visible if (signature == null || constructor.Name == ".cctor") return; XmlElement member = document.CreateElement ("Member"); member.SetAttribute ("MemberName", constructor_name); members.AppendChild (member); XmlElement constructor_signature = document.CreateElement ("MemberSignature"); constructor_signature.SetAttribute ("Language", "C#"); constructor_signature.SetAttribute ("Value", signature); member.AppendChild (constructor_signature); member.AppendChild (AddElement (document, "MemberType", "Constructor")); Type return_type = constructor.DeclaringType; ParameterInfo [] parameters = constructor.GetParameters (); // constructors have an empty ReturnValue node. member.AppendChild (document.CreateElement ("ReturnValue")); member.AppendChild (AddParameters (document, parameters)); member.AppendChild (AddDocsNode (document, return_type, parameters)); }
public void EmitCtor(ConstructorInfo ctor) { if (ctor == null) throw new ArgumentNullException("ctor"); CheckAccessibility(ctor); il.Emit(OpCodes.Newobj, ctor); #if DEBUG_COMPILE Helpers.DebugWriteLine(OpCodes.Newobj + ": " + ctor.DeclaringType); #endif }
internal AccessStubConstructorMethodWrapper(TypeWrapper declaringType, string sig, ConstructorInfo core, ConstructorInfo stub, TypeWrapper[] parameterTypes, Modifiers modifiers, MemberFlags flags) : base(declaringType, StringConstants.INIT, sig, core, PrimitiveTypeWrapper.VOID, parameterTypes, modifiers, flags) { this.stub = stub; }
internal static ConstructorInfo AddAutomagicSerializationToWorkaroundBaseClass(TypeBuilder typeBuilderWorkaroundBaseClass, ConstructorInfo baseCtor) { if (typeBuilderWorkaroundBaseClass.BaseType.IsSerializable) { typeBuilderWorkaroundBaseClass.SetCustomAttribute(serializableAttribute); if (baseCtor != null && (baseCtor.IsFamily || baseCtor.IsFamilyOrAssembly)) { return AddConstructor(typeBuilderWorkaroundBaseClass, null, baseCtor, false); } } return null; }