private static MethodInfo GetMethodInfo(MethodInfo mi, MemberInfo memberInfo) { if (memberInfo is FieldInfo) { return mi.MakeGenericMethod ((memberInfo as FieldInfo).FieldType); } if (memberInfo is PropertyInfo) { return mi.MakeGenericMethod ((memberInfo as PropertyInfo).PropertyType); } return null; }
public object InvokeGenericMethod(MethodInfo genericMethodDefinition, Type[] genericArguments, object instance, object[] arguments) { Debug.Assert(genericMethodDefinition.IsGenericMethodDefinition); var method = genericMethodDefinition.MakeGenericMethod(genericArguments); return InvokeMethod(method, instance, arguments); }
private static Expression CreateCall(MethodInfo method, ParameterExpression handler, ParameterExpression context, Type handlerType) { if (method.IsGenericMethod) { var handlerParameterType = method.GetParameters()[0].ParameterType; if (handlerParameterType.IsGenericType) { var @interface = handlerType.GetInterfaces().FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == handlerParameterType.GetGenericTypeDefinition()); if (@interface != null) { method = method.MakeGenericMethod(@interface.GetGenericArguments().Single()); } } else { // bind handler as generic type? method = method.MakeGenericMethod(typeof(object)); //Debugger.Break(); } } return Expression.Call(method, handler, context); }
public void RandomTest() { const int IterationCount = 10; int iteration = 0; Random random = RandomManager.CreateRandom(SeedVariatorType.CallingMethod); MethodInfo setValueMethodGeneric = typeof(TupleBehaviorTestBase).GetMethod("SetValue", BindingFlags.NonPublic | BindingFlags.Static); IList <TupleDescriptor> descriptorList = new List <TupleDescriptor>(); while (iteration++ < IterationCount) { int fieldCount = random.Next(0, MaxFieldCount); List <Type> fields = new List <Type>(fieldCount); for (int i = 0; i < fieldCount; i++) { fields.Add(fieldTypes[random.Next(0, fieldTypes.Length - 1)]); } TupleDescriptor descriptor = TupleDescriptor.Create(fields); descriptorList.Add(descriptor); } foreach (TupleDescriptor descriptor in descriptorList) { DummyTuple dummyTuple = new DummyTuple(descriptor); ITuple tuple = CreateTestTuple(descriptor); for (int fieldIndex = 0; fieldIndex < tuple.Count / 2; fieldIndex++) { Type type = descriptor[fieldIndex]; MethodInfo setValueMethod = setValueMethodGeneric.MakeGenericMethod(type); setValueMethod.Invoke(null, new object[] { dummyTuple, tuple, fieldIndex, random }); } AssertAreSame(dummyTuple, tuple); } }
private Func <QueryContext, TResult> CreateCompiledQuery <TResult>(Expression query, bool extractParams) { if (extractParams) { using (QueryContext qc = this.queryContextFactory.Create()) { query = this.ExtractParameters(query, qc, false); } } Type sequenceType = Utils.QueryReturnsSingleResult(query) ? null : typeof(TResult) == typeof(IEnumerable) ? typeof(object) : Utils.TryGetSequenceType(typeof(TResult)); if (sequenceType == null) { return(qc => { try { return this.CreateCompiledEnumerableQuery <TResult>(query)(qc).First(); } catch (Exception exception) { this.logger.QueryIterationFailed(qc.Context.GetType(), exception); throw; } }); } else { return((Func <QueryContext, TResult>)CreateCompiledEnumerableQueryMethod.MakeGenericMethod(sequenceType) .Invoke(this, new object[] { query })); } }
private static T GetArray <T>(XmlElement etype) { Type type = typeof(T); if (type.IsArray) { XmlNodeList nodes = etype.SelectNodes("./data/value"); Type typeElements = type.GetElementType(); Array arrayToReturn = Array.CreateInstance(typeElements, nodes.Count); int index = 0; foreach (XmlNode valueNode in nodes) { foreach (XmlNode realvalue in valueNode.ChildNodes) { System.Reflection.MethodInfo mi = typeof(XmlRpcClient).GetMethod("GetValue", BindingFlags.Static | BindingFlags.NonPublic); mi = mi.MakeGenericMethod(typeElements); object[] @params = { realvalue }; object value = mi.Invoke(null, @params); arrayToReturn.SetValue(value, index); index++; } } return((T)System.Convert.ChangeType(arrayToReturn, type)); } else { throw new XmlRpcException("The value is incompatible"); } }
protected SaveChangesAction(IXenObject obj, bool suppressHistory) : base(obj.Connection, Messages.ACTION_SAVE_CHANGES_TITLE, Messages.ACTION_SAVE_CHANGES_IN_PROGRESS, suppressHistory) { // This is lovely. We need to lock the server object (not the copy we have taken) before calling save changes. // We don't know the type so we use the MethodInfo object and MakeGenericMethod to do a resolve against the type // we have extracted from GetType(). The Resolve() call itself needs a XenRef which we make by calling the XenRef constructor that takes the // opaque ref as an argument and using the MakeGenericType call to give it the same type as the object... // ... _then_ we lock it. SetObject(obj); _xenObject = obj; if (obj.opaque_ref != null) // creating a new object comes through here, but with obj.opaque_ref == null { System.Reflection.MethodInfo mi = typeof(IXenConnection).GetMethod("Resolve", BindingFlags.Public | BindingFlags.Instance); Type type = obj.GetType(); object[] xenRefParam = new object[] { typeof(XenRef <>).MakeGenericType(type).GetConstructor(new Type[] { typeof(string) }).Invoke(new Object[] { obj.opaque_ref }) }; _serverXenObject = (IXenObject)mi.MakeGenericMethod(type).Invoke(obj.Connection, xenRefParam); if (_serverXenObject != null) { // CA-35210: Removed this exception pending locking overhaul post MR in CA-38966 //if (_serverXenObject.Locked) // lockViolation = true; _serverXenObject.Locked = true; } } }
protected override ConstantExpression VisitConstant(ConstantExpression expression) { var nonGenericQueryArgument = expression.Value as VariableQueryArgument; if (!ReferenceEquals(null, nonGenericQueryArgument)) { var type = nonGenericQueryArgument.Type.Type; var value = nonGenericQueryArgument.Value; var queryArgument = Activator.CreateInstance(typeof(VariableQueryArgument <>).MakeGenericType(type), new[] { value }); return(new ConstantExpression(queryArgument)); } var nonGenericQueryArgumentList = expression.Value as VariableQueryArgumentList; if (!ReferenceEquals(null, nonGenericQueryArgumentList)) { var elementType = nonGenericQueryArgumentList.ElementType.Type; var values = nonGenericQueryArgumentList.Values; var methodInfo = CreateVariableQueryArgumentListMethodInfo.MakeGenericMethod(elementType); var queryArgument = methodInfo.Invoke(null, new object[] { values }); return(new ConstantExpression(queryArgument)); } return(base.VisitConstant(expression)); }
internal static MessagePackSerializer CreateInternal(SerializationContext context, Type targetType, PolymorphismSchema schema) { #if UNITY return (( Delegate.CreateDelegate( typeof(Func <SerializationContext, PolymorphismSchema, object>), CreateInternal_2.MakeGenericMethod(targetType) ) as Func <SerializationContext, PolymorphismSchema, object>)(context, schema) as MessagePackSerializer); #else return ((CreateInternal_2.MakeGenericMethod(targetType).CreateDelegate(typeof(Func <SerializationContext, PolymorphismSchema, object>)) as Func <SerializationContext, PolymorphismSchema, object>)(context, schema) as MessagePackSerializer); #endif // UNITY }
public void Method( MethodInfo mi , int argToTest) { var genericArgsInfo = mi.GetGenericArguments(); int aggregateCount = genericArgsInfo.Count(t => Regex.IsMatch(t.Name, "^TA")); if (genericArgsInfo.Length > 0) mi = mi.MakeGenericMethod(genericArgsInfo.Select( p => p.Name == "TSourceAggregates" ? typeof(Tuple<int, int>) : typeof(int)).ToArray()); var paramInfos = mi.GetParameters(); var callArguments = paramInfos.Select((p, i) => { object arg = null; if (p.ParameterType.IsValueType) arg = Activator.CreateInstance(p.ParameterType); else if (i < argToTest) arg = ConstructArgument(p.ParameterType, aggregateCount); return Expression.Constant(arg, p.ParameterType); }); Action callWithBoundArguments = Expression.Lambda<Action>(Expression.Call(mi, callArguments)).Compile(); Assert.That(new TestDelegate(callWithBoundArguments), Throws.TypeOf(typeof(ArgumentNullException)) .With.Property("ParamName").EqualTo(paramInfos[argToTest].Name)); }
/// <summary> /// Executes the <see cref="System.Linq.Expressions.Expression"/> and returns the raw result. /// </summary> /// <param name="expression">The <see cref="System.Linq.Expressions.Expression"/> to be executed.</param> /// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param> /// <returns>Execution result of the <see cref="System.Linq.Expressions.Expression"/> specified.</returns> protected async Task<object> ExecuteCoreAsync(System.Linq.Expressions.Expression expression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lambdaExpression = (expression as System.Linq.Expressions.LambdaExpression) ?? System.Linq.Expressions.Expression.Lambda(expression); var queryResult = lambdaExpression.Compile().DynamicInvoke(); if (queryResult is Task task) { queryResult = await GetTaskResultAsync(task).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); var queryableType = queryResult.GetType(); if (queryableType.Implements(typeof(IQueryable<>))) { // force query execution var elementType = TypeHelper.GetElementType(queryableType); task = (Task)ToListAsync.MakeGenericMethod(elementType).Invoke(null, new[] { queryResult, cancellationToken }); await task.ConfigureAwait(false); var result = TaskResultProperty(typeof(List<>).MakeGenericType(elementType)).GetValue(task); queryResult = result; } return queryResult; }
/// 根据数据源更新UI。(效率不高,不要频繁调用) public void UpdateUI() { foreach (var itemSource in m_itemSources) { if (itemSource != null) { var type = itemSource.GetType(); //获取带一个参数回调方法的TriggerEvent。 System.Reflection.MethodInfo mTriggerEvent = null; System.Reflection.MethodInfo[] methodInfoArray = m_eventController.GetType().GetMethods(); foreach(System.Reflection.MethodInfo mi in methodInfoArray) { if(mi.Name == "TriggerEvent" && mi.IsGenericMethod && mi.GetGenericArguments().Length == 1) { mTriggerEvent = mi; break; } } if(mTriggerEvent == null) return; foreach (var item in m_eventController.TheRouter) { var prop = type.GetProperty(item.Key); if (prop == null) continue; var method = mTriggerEvent.MakeGenericMethod(prop.PropertyType);//对泛型进行类型限定 var value = prop.GetGetMethod().Invoke(itemSource, null);//获取参数值 method.Invoke(m_eventController, new object[] { item.Key, value });//调用对应参数类型的触发方法 } } } }
/// <summary> /// Schreibt den Wert value in ein Property der instance mit dem propertyName, der Propertytype wird zur Laufzeit ermittelt /// </summary> /// <param name="instance"></param> /// <param name="value"></param> /// <param name="name"></param> public static void SetPropertyValue(object instance, string value, string propertyName) { PropertyInfo propertyInfo = PropertyReflectionHelper.GetPropertyInfo(instance, propertyName); MethodInfo setPropertyValue = typeof(PropertyReflectionHelper).GetMethod("SetPropertyValue"); MethodInfo setGenericSetPropertyValue = setPropertyValue.MakeGenericMethod(propertyInfo.PropertyType); if (string.IsNullOrEmpty(value)) { object[] args = { instance, propertyInfo.Name, null }; setGenericSetPropertyValue.Invoke(null, args); } else if (propertyInfo.PropertyType == typeof(Money)) { object[] args = { instance, propertyInfo.Name, Money.TryConvert(value) }; setGenericSetPropertyValue.Invoke(null, args); } else { Type conversionType = propertyInfo.PropertyType; if (TypeHelper.IsNullableType(conversionType)) { conversionType = TypeHelper.GetUnderlyingTypeOfNullable(conversionType); } object[] args = { instance, propertyInfo.Name, Convert.ChangeType(value, conversionType) }; setGenericSetPropertyValue.Invoke(null, args); } }
static OptionalTypeConverter() { optional = (from info in typeof(Prelude).GetMethods() where info.Name == "Optional" select info) .First(); methods = Prelude.memo((Type valueType) => optional.MakeGenericMethod(valueType)); }
/// <summary> /// Gibt den Propertywert zurück, der Typ wird in ein Object gecasted, der PropertyTyp wird zur Laufzeit ermittelt /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <returns></returns> public static object GetPropertyValue(object instance, string propertyName) { PropertyInfo propertyInfo = PropertyReflectionHelper.GetPropertyInfo(instance, propertyName); MethodInfo getPropertyValue = typeof(PropertyReflectionHelper).GetMethod("GetPropertyValue"); MethodInfo genericGetPropertyValue = getPropertyValue.MakeGenericMethod(propertyInfo.PropertyType); object[] args = { instance, propertyInfo.Name }; return(genericGetPropertyValue.Invoke(null, args)); }
static SomeTypeConverter() { someCreate = (from info in typeof(Some).GetMethods() where info.Name == "Create" select info) .First(); methods = Prelude.memo((Type valueType) => someCreate.MakeGenericMethod(valueType)); }
private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection<Expression> args, Type[] typeArgs) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length != args.Count) { return false; } if ((!m.IsGenericMethod && (typeArgs != null)) && (typeArgs.Length > 0)) { return false; } if ((!m.IsGenericMethodDefinition && m.IsGenericMethod) && m.ContainsGenericParameters) { m = m.GetGenericMethodDefinition(); } if (m.IsGenericMethodDefinition) { if ((typeArgs == null) || (typeArgs.Length == 0)) { return false; } if (m.GetGenericArguments().Length != typeArgs.Length) { return false; } m = m.MakeGenericMethod(typeArgs); parameters = m.GetParameters(); } int index = 0; int count = args.Count; while (index < count) { Type parameterType = parameters[index].ParameterType; if (parameterType == null) { return false; } if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); } Expression operand = args[index]; if (!parameterType.IsAssignableFrom(operand.Type)) { if (operand.NodeType == ExpressionType.Quote) { operand = ((UnaryExpression) operand).Operand; } if (!parameterType.IsAssignableFrom(operand.Type) && !parameterType.IsAssignableFrom(StripExpression(operand.Type))) { return false; } } index++; } return true; }
private static void Add(this ConfigurationRegistrar configurationRegistrar,Type modelConfigurationType, Type modelType, MethodInfo addMethod) { if (modelType != null) { addMethod .MakeGenericMethod(modelType) .Invoke(configurationRegistrar, new[] { Activator.CreateInstance(modelConfigurationType) }); } }
public void ShouldMatchGenericParameters() { targetMethod = typeof(MethodFinderTargetDummy).GetMethod("DoSomethingGeneric"); Assert.IsTrue(targetMethod.IsGenericMethodDefinition); Type typeArgument = typeof(int); targetMethod = targetMethod.MakeGenericMethod(typeArgument); builder.TypeArguments.Add(typeArgument); RunTest(); }
public Case(MethodInfo caseMethod, params object[] parameters) { this.parameters = parameters != null && parameters.Length == 0 ? null : parameters; Class = caseMethod.ReflectedType; Method = caseMethod.IsGenericMethodDefinition ? caseMethod.MakeGenericMethod(GenericArgumentResolver.ResolveTypeArguments(caseMethod, parameters)) : caseMethod; Name = GetName(); }
private Func <QueryContext, IEnumerable <TItem> > CreateCompiledEnumerableQuery <TItem>(Expression query) { var preparedQuery = new PreparedQuery(query, this.EntityTypeMap); return(queryContext => { object items = preparedQuery.Execute <TItem>(queryContext); items = InterceptExceptionsMethod.MakeGenericMethod(typeof(TItem)) .Invoke(null, new[] { items, queryContext.Context.GetType(), this.logger, queryContext }); return (IEnumerable <TItem>)items; }); }
void readData() { selectedData = 0; lastSelectedData = -1; objectsLists = new List <IList>(); //DataString removeData = null; List <DataString> removeData = new List <DataString>(); foreach (var data in datas) { if (data.directory == "") { removeData.Add(data); //Debug.LogError("No directory "); continue; } try { object[] parameters = new object[1]; parameters[0] = RESOURCES_DIR + data.directory; System.Reflection.MethodInfo method = typeof(XmlReader).GetMethod("LoadXMLFrom"); System.Reflection.MethodInfo generic = method.MakeGenericMethod(System.Type.GetType(data.className + ",Assembly-CSharp")); IList list = (IList)generic.Invoke(null, parameters); /*foreach (var item in list.GetType().GetGenericArguments()[0].GetFields()) { * data.addFieldOptions(item.Name, item.FieldType.Name); * }*/ objectsLists.Add(list); } catch { removeData.Add(data); Debug.LogError(data.className + " Could not be loaded"); } } foreach (var item in removeData) { datas.Remove(item); } if (objectsLists.Count > 0) { changeSelectedData(); } selectedElement = 0; }
/// <summary> /// Takes the given <paramref name="genericMethodDefinition"/> and instantiates it, substituting its generic parameter with the value /// type of the value held by this object. The method must have exactly one generic parameter. /// </summary> /// <param name="genericMethodDefinition">The generic method definition to instantiate.</param> /// <returns> /// A closed generic instantiation of <paramref name="genericMethodDefinition"/> with this object's value type substituted for /// the generic parameter. /// </returns> public MethodInfo MakeClosedGenericExecuteMethod (MethodInfo genericMethodDefinition) { ArgumentUtility.CheckNotNull ("genericMethodDefinition", genericMethodDefinition); if (!genericMethodDefinition.IsGenericMethodDefinition) throw new ArgumentException ("GenericMethodDefinition must be a generic method definition.", "genericMethodDefinition"); if (genericMethodDefinition.GetGenericArguments ().Length != 1) throw new ArgumentException ("GenericMethodDefinition must have exactly one generic parameter.", "genericMethodDefinition"); return genericMethodDefinition.MakeGenericMethod (DataType); }
void DrawToolbar(int windowID) { GUILayout.Label("Add Node"); nodeTypeScrollPosition = GUILayout.BeginScrollView( nodeTypeScrollPosition); foreach (KeyValuePair <NodeDescription.Type, List <System.Type> > kvp in NodeTypes) { NodeFoldouts[(int)kvp.Key] = EditorGUILayout.Foldout(NodeFoldouts[(int)kvp.Key], kvp.Key.ToString()); if (NodeFoldouts[(int)kvp.Key]) { foreach (System.Type t in kvp.Value) { string label = "Undefined Name"; System.Attribute[] attrs = (System.Attribute[])t.GetCustomAttributes(false); foreach (System.Attribute attr in attrs) { if (attr is NodeDescription) { label = ((NodeDescription)attr).GetName(); } } if (GUILayout.Button(label)) { System.Reflection.MethodInfo method = this.GetType().GetMethod("AddNode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); System.Reflection.MethodInfo generic = method.MakeGenericMethod(new System.Type[] { t }); generic.Invoke(this, null); } } } } GUILayout.EndScrollView(); if (GUILayout.Button("Clear All")) { if (nodes != null) { foreach (MarrowNode node in nodes) { DestroyImmediate(node); } inspected = null; nodes.Clear(); } } GUI.DragWindow(); }
public bool InitializeProxyMethod(MethodInfo sourceMethod, Type[] types, out MethodInfo proxyMethod) { var proxyType = this.ProxyType; if (types == null) throw new ArgumentOutOfRangeException("types"); var proxyTypeArgs = new List<Type>(); if (ReflectionHelper.IsGenericType(sourceMethod.DeclaringType)) { proxyTypeArgs.AddRange(sourceMethod.DeclaringType.GetTypeInfo().GenericTypeArguments); } if (sourceMethod.IsGenericMethod) { proxyTypeArgs.AddRange(sourceMethod.GetGenericArguments()); } var typeArrayPointer = 0; if (proxyType.IsGenericTypeDefinition) { var typeArgs = new Type[proxyType.GenericTypeParameters.Length]; for (int i = 0; i < typeArgs.Length; i++) { typeArgs[i] = proxyTypeArgs[typeArrayPointer]; typeArrayPointer++; } proxyType = proxyType.MakeGenericType(typeArgs).GetTypeInfo(); } if (proxyTypeArgs.Count == typeArrayPointer) { proxyMethod = proxyType.GetDeclaredMethods(MethodName).FirstOrDefault(m => CheckTypes(m.GetParameters(), types)); } else { var typeArgs = new Type[proxyTypeArgs.Count - typeArrayPointer]; for (int i = 0; i < typeArgs.Length; i++) { typeArgs[i] = proxyTypeArgs[typeArrayPointer]; typeArrayPointer++; } proxyMethod = proxyType.GetDeclaredMethods(MethodName).FirstOrDefault(m => { if (!m.IsGenericMethodDefinition || m.GetGenericArguments().Length != typeArgs.Length) return false; var genericMethod = m.MakeGenericMethod(typeArgs); return CheckTypes(genericMethod.GetParameters(), types); }); if (proxyMethod != null) { proxyMethod = proxyMethod.MakeGenericMethod(typeArgs); return true; } } if (proxyMethod == null) return false; return true; }
public BindDelegateExpression(Type @delegate, Expression owner, MethodInfo methodToBindTo, GenericTypeParameterBuilder[] genericTypeParams) { delegateCtor = @delegate.GetConstructors()[0]; this.methodToBindTo = methodToBindTo; if(@delegate.IsGenericTypeDefinition) { var closedDelegate = @delegate.MakeGenericType(genericTypeParams); delegateCtor = TypeBuilder.GetConstructor(closedDelegate, delegateCtor); this.methodToBindTo = methodToBindTo.MakeGenericMethod(genericTypeParams); } this.owner = owner; }
public void OnPointerExit(PointerEventData eventData) { try { System.Reflection.MethodInfo method = typeof(PanelManager).GetMethod("TogglePanel"); method.MakeGenericMethod(new Type[] { Type.GetType(strClass) }).Invoke(PanelManager.instance, new object[1]); } catch (Exception e) { Debug.Log(e); } }
internal MethodInfo GainMethod() { if (Info != null) { return Info; } Info = GainBase(); if(GenericParameter.Count > 0) { Info = Info.MakeGenericMethod(GenericParameter.GainTypes()); } return Info; }
protected static void PopulateData(IList <Type> types, Xtensive.Tuples.Tuple tuple) { Random random = RandomManager.CreateRandom(SeedVariatorType.CallingMethod); MethodInfo setValueMethodGeneric = typeof(TupleBehaviorTestBase).GetMethod("InternalSetValue", BindingFlags.NonPublic | BindingFlags.Static); for (int fieldIndex = 0; fieldIndex < tuple.Count; fieldIndex++) { Type type = types[fieldIndex % types.Count]; MethodInfo setValueMethod = setValueMethodGeneric.MakeGenericMethod(type); setValueMethod.Invoke(null, new object[] { tuple, fieldIndex, random }); } }
public static Delegate GetDelegate(MethodInfo openMethod, Type eventType, Type payloadType) { var closedMethod = openMethod.MakeGenericMethod(eventType); return _cache.GetOrAdd(closedMethod, (m) => { var param = Expression.Parameter(eventType); var call = Expression.Call(param, closedMethod); var lambda = Expression.Lambda(call, param); return lambda.Compile(); }); }
protected static void AddClientSideEval(MethodInfo target, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree) { target = target.MakeGenericMethod(queryModelVisitor.CurrentEvaluationType.DataType); var parameter = Expression.Parameter(queryModelVisitor.PreviousEvaluationType.DataType, null); var lambda = Expression.Lambda( Expression.Call( target, parameter), parameter); tree.AddPostExecuteTransformer(lambda); }
public Case(MethodInfo caseMethod, params object[] parameters) { Parameters = parameters != null && parameters.Length == 0 ? null : parameters; Class = caseMethod.ReflectedType; Method = caseMethod.IsGenericMethodDefinition ? caseMethod.MakeGenericMethod(GenericArgumentResolver.ResolveTypeArguments(caseMethod, parameters)) : caseMethod; MethodGroup = new MethodGroup(caseMethod); Name = GetName(); exceptions = new List<Exception>(); }
protected static void AddClientSideEval(MethodInfo target, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree) { var type = queryModelVisitor.Model.SelectClause.Selector.Type; target = target.MakeGenericMethod(type); var parameter = Expression.Parameter(typeof(IQueryable<>).MakeGenericType(type), null); var lambda = Expression.Lambda( Expression.Call( target, parameter), parameter); tree.AddPostExecuteTransformer(lambda); }
private static DeserializationInvokeHandler GetDeserializationInvoker(TypeBuilder tb, MethodInfo methodInfo, Type val_type, int typeID) { DynamicMethod dynamicMethod = null; ILGenerator il; #if GENERATE_DEBUGGING_ASSEMBLY if (tb != null) { var methodBuilder = DeserializerCodegen.GenerateStaticDeserializeInvokerStub(tb, typeID); il = methodBuilder.GetILGenerator(); } else #endif { dynamicMethod = DeserializerCodegen.GenerateDynamicDeserializeInvokerStub(); il = dynamicMethod.GetILGenerator(); } var local = il.DeclareLocal(val_type); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldloca_S, local); il.Emit(OpCodes.Ldarg_2); if (methodInfo.IsGenericMethodDefinition) { Debug.Assert(val_type.IsGenericType); var genArgs = val_type.GetGenericArguments(); il.EmitCall(OpCodes.Call, methodInfo.MakeGenericMethod(genArgs), null); } else { il.EmitCall(OpCodes.Call, methodInfo, null); } // write result object to out object il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldloc_S, local); if (val_type.IsValueType) il.Emit(OpCodes.Box, val_type); il.Emit(OpCodes.Stind_Ref); il.Emit(OpCodes.Ret); if (tb != null) return null; else return (DeserializationInvokeHandler)dynamicMethod.CreateDelegate(typeof(DeserializationInvokeHandler)); }
public void OnPointerEnter(PointerEventData eventData) { KeyValuesUpdate kv = new KeyValuesUpdate("ShowIntro", content); //利用反射调用泛型方法,因为字符串无法作为类传进泛型 try { System.Reflection.MethodInfo method = typeof(PanelManager).GetMethod("TogglePanel"); method.MakeGenericMethod(new Type[] { Type.GetType(strClass) }).Invoke(PanelManager.instance, new object[1]); MessageCenter.instance.SendMessage(strClass, kv); } catch (Exception e) { Debug.Log(e); } }
internal WSAccessKeyEntity GenerateWSAccessKey() { WSAccessKeyEntity key = null; if (Request.Security.IsLogged && Request.Security.AuthToken.User.role >= WSConstants.ACCESS_LEVEL.ADMIN && Request.INPUT.Any(x => WSConstants.ALIACES.USER_ID.Match(x.Key))) { using (WSDataContext DBContext = GetInternalContext(Request.Meta.DB, Request.ID, $"{GetType().Name}.GenerateWSAccessKey()")) { string UserID = Request.INPUT.ReadValue(WSConstants.ALIACES.USER_ID, out UserID) ? UserID : null; Func <Type, bool> userFunc = a => a.Name.Equals("User"); PropertyInfo sessionProp = /*Request.*/ DBContext .GetType() .GetProperties() .FirstOrDefault(x => x.PropertyType.GetGenericTypeArguments().Any(userFunc)); Type userType = sessionProp == null ? null : sessionProp .PropertyType .GetGenericTypeArguments() .FirstOrDefault(userFunc); if (userType != null) { System.Reflection.MethodInfo mInfo = /*Request.*/ DBContext.GetType().GetMethod("GetTable", new Type[] { }); var UObj = mInfo.MakeGenericMethod(new Type[] { userType }).Invoke(/*Request.*/ DBContext, new object[] { }); Func <WSDynamicEntity, bool> func = s => s.getIdentities(ClientFunctions).FirstOrDefault(i => i.Key.ToLower().Equals("userid")).Value.ToString().ToLower().Equals(UserID.ToLower()); System.Reflection.MethodInfo[] methods = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); var method = methods.FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(WSDynamicEntity)); WSDynamicEntity user = (WSDynamicEntity)method.Invoke(null, new object[] { UObj, func }); if (user != null) { object pass = null; if (user.TryReadPropertyValue("Password", out pass)) { key = new WSAccessKeyEntity(UserID.ToLower(), Request.Security.generateKey(new string[] { UserID.ToLower(), pass.ToString() })); } } } } } return(key); }
public static IntPtr MakeGenericMethod(MethodInfo method, Type[] typeArgs) { if (method == null) throw new ArgumentNullException("method"); if (typeArgs == null) throw new ArgumentNullException("typeArgs"); if (!method.IsGenericMethodDefinition) throw new ArgumentException("The method is not a generic method definition", "method"); var typeParams = method.GetGenericArguments(); if (typeParams.Length != typeArgs.Length) throw new ArgumentException("An invalid amount of type arguments was specified", "typeArgs"); return method.MakeGenericMethod(typeArgs).MethodHandle.Value; }
void saveData() { if (objectsLists == null) { return; } if (objectsLists.Count == 0) { return; } if (objectsLists[selectedData].Count == 0) { return; } //XmlReader.SaveXml(DATA_FILE, datas); XmlReader.SaveXmlTo(DATA_DIR, DATA_FILE, datas); var listInstance = (IList)typeof(List <>) .MakeGenericType(objectsLists[selectedData].GetType().GetGenericArguments()[0]) .GetConstructor(System.Type.EmptyTypes) .Invoke(null); foreach (var item in objectsLists[selectedData]) { listInstance.Add(item); } object[] parameters = new object[3]; parameters[0] = RESOURCES_DIR; parameters[1] = datas[selectedData].directory; //ResourcesLoader.LOADER_DIR + MansionRoomMng.ROOMS_F; parameters[2] = listInstance; System.Reflection.MethodInfo method = typeof(XmlReader).GetMethod("SaveXmlTo"); System.Reflection.MethodInfo generic = method.MakeGenericMethod(objectsLists[selectedData].GetType().GetGenericArguments()[0]); generic.Invoke(null, parameters); //XmlReader.SaveXml("Assets/Resources/" + ResourcesLoader.LOADER_DIR + MansionRoomMng.ROOMS_F, list); AssetDatabase.Refresh(); }
private Func <QueryContext, IAsyncEnumerable <TResult> > CreateCompiledAsyncEnumerableQuery <TResult>(Expression query, bool extractParams) { if (extractParams) { using (QueryContext qc = this.queryContextFactory.Create()) { query = this.ExtractParameters(query, qc, false); } } var preparedQuery = new PreparedQuery(query, this.EntityTypeMap); return(queryContext => { IAsyncEnumerable <TResult> result = preparedQuery.ExecuteAsync <TResult>(queryContext); return (IAsyncEnumerable <TResult>)AsyncInterceptExceptionsMethod.MakeGenericMethod(typeof(TResult)) .Invoke(null, new object[] { result, queryContext.Context.GetType(), this.logger, queryContext }); }); }
// this function is for finding singletons. // unity has a function called GameObject.FindObjectOfType(T) that does it // but it changed over the years to GameObject.FindObjectOfType<T>() // so we have to use reflection to get it. We can supply via pointer since its impossible to make a delegate that is generic // so this code forces the new versions of unity to use the old prototype public static UnityEngine.Object FindObjectOfType(System.Type T) { #if OLDOBJECTFINDER return(GameObject.FindObjectOfType(T)); #else System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.FlattenHierarchy; System.Reflection.MethodInfo method = null; foreach (var m in typeof(GameObject).GetMethods(flags)) { if (m.Name == "FindObjectOfType" && m.GetParameters().Length == 0) { method = m; break; } } System.Reflection.MethodInfo _FindObjectOfType = method.MakeGenericMethod(T); return((UnityEngine.Object)_FindObjectOfType.Invoke(null, null)); #endif }
public static Delegate GetGenericMethod(MethodInfo methodInfo, params Type[] genericTypes) { string joinToString = genericTypes.Select(t => t.FullName).JoinToString("-"); string key = GetKeyName(methodInfo.DeclaringType.FullName, string.Format("{0}{1}", methodInfo.Name, joinToString)); Delegate methodDelegate; if (CacheContainer.ContainsKey(key)) { methodDelegate = (Delegate)CacheContainer[key]; } else { methodInfo = methodInfo.MakeGenericMethod(genericTypes); methodDelegate = CreateMethod(methodInfo); CacheContainer.Add(key, methodDelegate); } return methodDelegate; }
/// <summary> /// InvokeAsync /// </summary> public Task <object> InvokeAsync(MethodDescriptor method, IDictionary <string, string> headers, object requestObject) { object requests; if (requestObject != null && typeof(IEnumerable <>).MakeGenericType(method.InputType.ClrType).IsAssignableFrom(requestObject.GetType())) { requests = requestObject; } else { Array ary = Array.CreateInstance(method.InputType.ClrType, 1); ary.SetValue(requestObject, 0); requests = ary; } System.Reflection.MethodInfo m = typeof(MethodDescriptorClient).GetMethod("CallGrpcAsyncCore", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); Task <object> task = (Task <object>)m.MakeGenericMethod(new Type[] { method.InputType.ClrType, method.OutputType.ClrType }).Invoke(this, new object[] { method, headers, requests }); return(task); }
protected override ConstantExpression VisitConstant(ConstantExpression node) { if (node.CheckNotNull(nameof(node)).Value is VariableQueryArgument nonGenericQueryArgument) { var type = nonGenericQueryArgument.Type.Type; var value = nonGenericQueryArgument.Value; var queryArgument = Activator.CreateInstance(typeof(VariableQueryArgument <>).MakeGenericType(type), new[] { value }); return(new ConstantExpression(queryArgument)); } if (node.Value is VariableQueryArgumentList nonGenericQueryArgumentList) { var elementType = nonGenericQueryArgumentList.ElementType.Type; var values = nonGenericQueryArgumentList.Values; var methodInfo = CreateVariableQueryArgumentListMethodInfo.MakeGenericMethod(elementType); var queryArgument = methodInfo.Invoke(null, new object[] { values }); return(new ConstantExpression(queryArgument)); } return(base.VisitConstant(node)); }
private static T GetStruct <T>(XmlElement etype) { Type type = typeof(T); XmlNodeList list = etype.SelectNodes("./member"); T t = Activator.CreateInstance <T>(); foreach (XmlElement e in list) { XmlElement eName = (XmlElement)e.SelectSingleNode("./name"); XmlElement eValue = (XmlElement)e.SelectSingleNode("./value"); FieldInfo field = type.GetField(eName.InnerText); Debug.Assert(field != null, "A field was not found", "The field " + eName.InnerText + " was not found in " + type.Name); System.Reflection.MethodInfo mi = typeof(XmlRpcClient).GetMethod("GetValue", BindingFlags.Static | BindingFlags.NonPublic); Type[] _params = { field.FieldType }; mi = mi.MakeGenericMethod(_params); object[] @params = { eValue.ChildNodes[0] }; object value = mi.Invoke(null, @params); field.SetValue(t, value); } return(t); }
/// <summary> /// Registers a generic method to handle all incoming events for given types from the Hub. /// </summary> /// <param name="eventTypes">The types of events to handle</param> /// <param name="instance">the instance on which to invoke <paramref name="handlerInfo"/>. in other words instance of the class taht defines the handler</param> /// <param name="handlerInfo">Method info for the generic event that is to handle the events. signature void(event).</param> //TODO could i make the MethodInfo parameter an expression pointing to the method public static void RegisterGenericHandler(this IHubProxy hubProxy, Type[] eventTypes, object instance, MethodInfo handlerInfo) { foreach (var eventType in eventTypes) { var eventName = EventName(eventType); //get the On<TEvent>(string, Action<TEvent>) method for "subscribing" to events coming from the server var onMethod = typeof(SignalR.Client.Hubs.HubProxyExtensions).GetMethods() .SingleOrDefault(x => x.Name == "On" && x.IsGenericMethod && x.GetParameters().Length == 3 && x.GetGenericArguments().Length == 1); if (onMethod == null) throw new Exception("Unable to find the On method on HubProxy(Extensions)"); var genericPublishMethod = handlerInfo.MakeGenericMethod(eventType); //create a delegate to invoke from On() method. as far as i know there is no other way var delegateType = typeof(Action<>).MakeGenericType(eventType); var handlerDelegate = Delegate.CreateDelegate(delegateType, instance, genericPublishMethod); var genericMethod = onMethod.MakeGenericMethod(eventType); //invoke/register genericMethod.Invoke(hubProxy, new object[] { hubProxy, eventName, handlerDelegate }); } }
private object[] GenerateArgs(IEnumerable <object> argList, IEnumerable <object> paramsList) { int argCount = Parameters.Count; var array = new object[Parameters.Count]; if (HasVarArgs) { argCount--; } int i = 0; foreach (var arg in argList) { if (i == argCount) { throw new InvalidOperationException("Command was invoked with too many parameters"); } array[i++] = arg; } if (i < argCount) { throw new InvalidOperationException("Command was invoked with too few parameters"); } if (HasVarArgs) { var func = _arrayConverters.GetOrAdd(Parameters[Parameters.Count - 1].Type, t => { var method = _convertParamsMethod.MakeGenericMethod(t); return((Func <IEnumerable <object>, object>)method.CreateDelegate(typeof(Func <IEnumerable <object>, object>))); }); array[i] = func(paramsList); } return(array); }
public virtual IMethod GetMethodT(string funcname, MethodParamList ttypes, MethodParamList types) { if (funcname == "CompareExchange") { return(new Method_Common_System(this, typeof(CustomMethod).GetMethod("CompareExchange"))); } //这个实现还不完全 //有个别重构下,判定比这个要复杂 System.Reflection.MethodInfo _method = null; var ms = TypeForSystem.GetMethods(); { var __array4 = ms; var __arrayLength4 = __array4.Length; for (int __i4 = 0; __i4 < __arrayLength4; ++__i4) { var m = __array4[__i4]; { if (m.Name == funcname && m.IsGenericMethodDefinition) { var ts = m.GetGenericArguments(); var ps = m.GetParameters(); if (ts.Length == ttypes.Count && ps.Length == types.Count) { _method = m; break; } } } } } // _method = TypeForSystem.GetMethod(funcname, types.ToArraySystem()); return(new Method_Common_System(this, _method.MakeGenericMethod(ttypes.ToArraySystem()))); }
static StackObject *MakeGenericMethod_11(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Type[] @typeArguments = (System.Type[]) typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.MethodInfo instance_of_this_method = (System.Reflection.MethodInfo) typeof(System.Reflection.MethodInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.MakeGenericMethod(@typeArguments); object obj_result_of_this_method = result_of_this_method; if (obj_result_of_this_method is CrossBindingAdaptorType) { return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance)); } return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
private static NotificationAsyncHandler BuildGenericAsyncHandler( Type targetType, Type invokePayloadType, MethodInfo method, FilterChain filterChain) { var argTypes = invokePayloadType.GetGenericArguments(); var genericMethod = method.MakeGenericMethod(argTypes.Skip(argTypes.Length - method.GetGenericArguments().Length).ToArray()); return BuildAsyncHandler(targetType, invokePayloadType, genericMethod, filterChain); }
/// <summary> /// Returns the generic <see cref="DbSet{T}"/> for the type specified. /// </summary> /// <returns>Returns an instance of type <see cref="DbSet{T}"/>.</returns> private static Func<Type, IQueryable> GetQueryableSetProvider(DbContext dbContext) => (Type type) => { var method = DbContextSetMethod.MakeGenericMethod(type); var set = method.Invoke(dbContext, new object[0]); return (IQueryable)set; };
private static bool ArgsMatch(MethodInfo methodInfo, IList<Expression> arguments, Type[] typeArgs) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length != arguments.Count) { return false; } if (!methodInfo.IsGenericMethod && typeArgs != null && typeArgs.Length > 0) { return false; } if (!methodInfo.IsGenericMethodDefinition && methodInfo.IsGenericMethod && methodInfo.ContainsGenericParameters) { methodInfo = methodInfo.GetGenericMethodDefinition(); } if (methodInfo.IsGenericMethodDefinition) { if (typeArgs == null || typeArgs.Length == 0) { return false; } if (methodInfo.GetGenericArguments().Length != typeArgs.Length) { return false; } methodInfo = methodInfo.MakeGenericMethod(typeArgs); parameters = methodInfo.GetParameters(); } for (int i = 0; i < arguments.Count; i++) { Type parameterType = parameters[i].ParameterType; if (parameterType == null) { return false; } if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); } Expression operand = arguments[i]; if (!parameterType.IsAssignableFrom(operand.Type)) { if (operand.NodeType == ExpressionType.Quote) { operand = ((UnaryExpression)operand).Operand; } if (!parameterType.IsAssignableFrom(operand.Type) && !parameterType.IsAssignableFrom(StripExpression(operand.Type))) { return false; } } } return true; }
protected static Delegate CreatePacketHandlerDelegate( PacketRegistrationType registrationType, Type packetType, MethodInfo handler ) { try { Type delegateType = null; switch ( registrationType ) { case PacketRegistrationType.Static: delegateType = typeof( ReceivePacketStatic<> ); break; case PacketRegistrationType.Instance: delegateType = typeof( ReceivePacketInstance<> ); break; case PacketRegistrationType.Timespan: delegateType = typeof( ReceivePacketTimespan<> ); break; default: return null; } delegateType = delegateType.MakeGenericType( packetType ); handler = handler.MakeGenericMethod( packetType ); Delegate action = Delegate.CreateDelegate( delegateType, handler ); return action; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); return null; } }
private static MethodInfo MakeGeneric(MethodInfo methodToMakeGeneric, MethodInfo originalMethod) { if (!methodToMakeGeneric.IsGenericMethodDefinition) { return methodToMakeGeneric; } return methodToMakeGeneric.MakeGenericMethod(originalMethod.GetGenericArguments()); }
private async Task ExecuteTestMethod(MethodInfo runtimeMethod, RunSummary runSummary, IEnumerable <WebDriverAttribute> driverAttributes, object[] dataRow) { foreach (var driverAttribute in driverAttributes) { foreach (var driver in driverAttribute.GetDrivers(runtimeMethod)) { Fixture newFixture = null; object initializerReturn = null; ITypeInfo[] resolvedTypes = null; var methodToRun = runtimeMethod; if (methodToRun.IsGenericMethodDefinition) { resolvedTypes = TestCase.TestMethod.Method.ResolveGenericTypes(dataRow); methodToRun = methodToRun.MakeGenericMethod(resolvedTypes.Select(t => ((IReflectionTypeInfo)t).Type).ToArray()); } List <object> parameterList = new List <object>(); var parameters = methodToRun.GetParameters().ToArray(); try { newFixture = FixtureCreationAttribute.GetNewFixture(driver, runtimeMethod); var initializeDataAttributes = ReflectionHelper.GetAttributes <FixtureInitializationAttribute>(runtimeMethod); foreach (var initializeDataAttribute in initializeDataAttributes) { if (initializeDataAttribute is IMethodInfoAware) { #if DNX var property = initializeDataAttribute.GetType().GetRuntimeProperty("Method"); property.SetValue(initializeDataAttribute, runtimeMethod); #else ((IMethodInfoAware)initializeDataAttribute).Method = runtimeMethod; #endif } initializeDataAttribute.Initialize(newFixture.Data); } var initializeAttribute = ReflectionHelper.GetAttribute <IFixtureInitializationAttribute>(runtimeMethod); if (initializeAttribute != null) { initializerReturn = initializeAttribute.Initialize(runtimeMethod, newFixture); } int dataRowIndex = 0; for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; var attributes = parameter.GetCustomAttributes(true); if (parameter.ParameterType == typeof(IWebDriver)) { parameterList.Add(driver); } else if (parameter.ParameterType == typeof(Fixture)) { parameterList.Add(newFixture); } else if (attributes.Any(a => a is GenerateAttribute)) { var generateAttribute = (GenerateAttribute)attributes.First(a => a is GenerateAttribute); InitializeCustomAttribute(generateAttribute, runtimeMethod, parameter); var constraintName = generateAttribute.ConstraintName ?? parameter.Name; var min = generateAttribute.Min; var max = generateAttribute.Max; var value = newFixture.Data.Generate(parameter.ParameterType, constraintName, new { min, max }); parameterList.Add(value); } else if (attributes.Any(a => a is LocateAttribute)) { var locateAttribute = (LocateAttribute)attributes.First(a => a is LocateAttribute); InitializeCustomAttribute(locateAttribute, runtimeMethod, parameter); var value = locateAttribute.Value; if (value == null) { value = newFixture.Data.Generate(new SimpleFixture.DataRequest(null, newFixture.Data, parameter.ParameterType, parameter.Name, false, null, null)); } parameterList.Add(value); } else if (attributes.Any(a => a is FreezeAttribute)) { var freeze = (FreezeAttribute)attributes.FirstOrDefault(a => a is FreezeAttribute); InitializeCustomAttribute(freeze, runtimeMethod, parameter); var value = freeze.Value; if (value == null) { var constraintName = freeze.ConstraintName ?? parameter.Name; var min = freeze.Min; var max = freeze.Max; value = newFixture.Data.Generate(parameter.ParameterType, constraintName, new { min, max }); } parameterList.Add(value); object lastObject = parameterList.Last(); var closedFreezeMethod = FreezeMethod.MakeGenericMethod(lastObject.GetType()); closedFreezeMethod.Invoke(null, new object[] { newFixture.Data, value, freeze.For }); } else if (initializerReturn != null && parameter.ParameterType == initializerReturn.GetType()) { parameterList.Add(initializerReturn); initializerReturn = null; } else if (dataRowIndex < dataRow.Length) { var dataValue = dataRow[dataRowIndex]; dataRowIndex++; parameterList.Add(dataValue); } else { var value = newFixture.Data.Generate(parameter.ParameterType, parameter.Name); parameterList.Add(value); } } } catch (Exception exp) { Aggregator.Add(exp); } var convertedDataRow = Reflector.ConvertArguments(parameterList.ToArray(), parameters.Select(p => p.ParameterType).ToArray()); var theoryDisplayName = TestCase.TestMethod.Method.GetDisplayNameWithArguments(DisplayName + " " + GetDriverName(driver), dataRow, resolvedTypes); var test = new XunitTest(TestCase, theoryDisplayName); var skipReason = SkipReason; XunitTestRunner testRunner = CreateTestRunner(test, MessageBus, TestClass, ConstructorArguments, methodToRun, convertedDataRow, skipReason, BeforeAfterAttributes, Aggregator, CancellationTokenSource); runSummary.Aggregate(await testRunner.RunAsync()); var timer = new ExecutionTimer(); timer.Aggregate(() => DisposeOfData(driverAttribute, driver, newFixture, dataRow)); runSummary.Time += timer.Total; } } }
public static T FromXML <T>(XmlNode Xml, IFormatProvider Provider) where T : new() { Type TypeEntity = typeof(T); T Entity = new T(); //List<> of Types if (TypeEntity.IsGenericType && typeof(System.Collections.IList).IsAssignableFrom(TypeEntity.GetGenericTypeDefinition())) { foreach (XmlNode node in Xml.ChildNodes) { object ret = node.InnerXml; if (node.NodeType != XmlNodeType.XmlDeclaration) { Type UnderlyingType = TypeEntity.GetGenericArguments()[0]; Type[] BasicTypes = { typeof(String), typeof(Int16), typeof(Int32), typeof(Int64), typeof(Boolean), typeof(DateTime), typeof(System.Char), typeof(System.Decimal), typeof(System.Double), typeof(System.Single), typeof(System.TimeSpan), typeof(System.Byte) }; //If not a basic Type , try to deep more in the dom tree deserializing the inner XML Value if (BasicTypes.SingleOrDefault((t) => { return(t == UnderlyingType); }) == null) { //Otherwise of arrays convert to XML to send var fromXMLMethods = typeof(Gale.Serialization).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); System.Reflection.MethodInfo fromXMLMethodInfo = fromXMLMethods.FirstOrDefault(mi => mi.Name == "FromXML" && mi.GetGenericArguments().Count() == 1 && mi.GetParameters()[0].ParameterType == typeof(XmlNode)); System.Reflection.MethodInfo method = fromXMLMethodInfo.MakeGenericMethod(new Type[] { UnderlyingType }); ret = method.Invoke(null, new object[] { node }); } (Entity as System.Collections.IList).Add(Convert.ChangeType(ret, UnderlyingType)); } } return((T)Entity); } List <PropertyInfo> setterProperties = (from PropertyInfo p in TypeEntity.GetProperties() where p.GetIndexParameters().Count() == 0 select p).ToList(); //Delegate Action <PropertyInfo, object> setValue = (Property, Value) => { try { Property.SetValue(Entity, Value, null); } catch { throw new Gale.Exception.GaleException("InvalidSetValueInXMLDeserialization", Value.ToString(), Property.Name, Property.PropertyType.ToString()); } }; //For Each setterProperties.ForEach((prop) => { if (object.ReferenceEquals(prop.DeclaringType, TypeEntity)) { System.Xml.Serialization.XmlAttributeAttribute customAttribute = (System.Xml.Serialization.XmlAttributeAttribute)prop.GetCustomAttributes(typeof(System.Xml.Serialization.XmlAttributeAttribute), false).FirstOrDefault(); Type propertyType = prop.PropertyType; string nodeValue = null; System.Xml.XmlNode noderef = null; if (customAttribute != null) { XmlAttribute attrib = Xml.Attributes[customAttribute.AttributeName]; if (attrib != null) { nodeValue = attrib.InnerXml; } } else { System.Xml.Serialization.XmlElementAttribute xmlattrib = (System.Xml.Serialization.XmlElementAttribute)prop.GetCustomAttributes(typeof(System.Xml.Serialization.XmlElementAttribute), false).FirstOrDefault(); XmlNode propertyNode = Xml.SelectSingleNode((xmlattrib != null) ? xmlattrib.ElementName : prop.Name); if (propertyNode != null) { noderef = propertyNode; nodeValue = propertyNode.InnerXml; } } if (nodeValue != null && nodeValue != String.Empty) { if (Type.Equals(propertyType, typeof(decimal))) { setValue(prop, System.Convert.ToDecimal(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(double))) { setValue(prop, System.Convert.ToDouble(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(Int16))) { setValue(prop, System.Convert.ToInt16(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(Int32))) { setValue(prop, System.Convert.ToInt32(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(Int64))) { setValue(prop, System.Convert.ToInt64(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(bool))) { setValue(prop, System.Convert.ToBoolean(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(DateTime))) { setValue(prop, System.Convert.ToDateTime(nodeValue, Provider)); } else if (Type.Equals(propertyType, typeof(string))) { setValue(prop, System.Convert.ToString(nodeValue, Provider)); } else if (propertyType.IsArray) { if (nodeValue != string.Empty) { Type UnderlyingType = propertyType.GetElementType(); //Array or a Generic List (Almost the same things) // Creates and initializes a new Array of type Int32. Array typedArray = Array.CreateInstance(UnderlyingType, noderef.ChildNodes.Count); int arrayIndex = 0; foreach (XmlNode node in noderef.ChildNodes) { object ret = node.InnerXml; if (node.NodeType != XmlNodeType.XmlDeclaration) { //If not a basic Type , try to deep more in the dom tree deserializing the inner XML Value Type[] BasicTypes = { typeof(String), typeof(Int16), typeof(Int32), typeof(Int64), typeof(Boolean), typeof(DateTime), typeof(System.Char), typeof(System.Decimal), typeof(System.Double), typeof(System.Single), typeof(System.TimeSpan), typeof(System.Byte) }; if (BasicTypes.SingleOrDefault((t) => { return(t == UnderlyingType); }) == null) { //Otherwise of arrays convert to XML to send var fromXMLMethods = typeof(Gale.Serialization).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); System.Reflection.MethodInfo fromXMLMethodInfo = fromXMLMethods.FirstOrDefault(mi => mi.Name == "FromXML" && mi.GetGenericArguments().Count() == 1 && mi.GetParameters()[0].ParameterType == typeof(XmlNode)); System.Reflection.MethodInfo method = fromXMLMethodInfo.MakeGenericMethod(new Type[] { UnderlyingType }); ret = method.Invoke(null, new object[] { node }); } typedArray.SetValue(Convert.ChangeType(ret, UnderlyingType), arrayIndex); } arrayIndex++; } setValue(prop, typedArray); } } else if (propertyType.IsGenericType) { //If a Parameter Type is Nullable, create the nullable type dinamycally and set it's value Type UnderlyingType = propertyType.GetGenericArguments()[0]; Type GenericDefinition = propertyType.GetGenericTypeDefinition(); Type GenericType = GenericDefinition.MakeGenericType(new Type[] { UnderlyingType }); object value = null; if (nodeValue != string.Empty) { if (GenericDefinition == typeof(System.Nullable <>)) { value = Convert.ChangeType(nodeValue, UnderlyingType); } else { //Complex Node Type, (Maybe it's a List of Other Complex Type and go on in the deepest level //So call the fromXML itself, again and again //Otherwise of arrays convert to XML to send var fromXMLMethods = typeof(Gale.Serialization).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); System.Reflection.MethodInfo fromXMLMethodInfo = fromXMLMethods.FirstOrDefault(mi => mi.Name == "FromXML" && mi.GetGenericArguments().Count() == 1 && mi.GetParameters()[0].ParameterType == typeof(XmlNode)); System.Reflection.MethodInfo method = fromXMLMethodInfo.MakeGenericMethod(new Type[] { GenericType }); value = method.Invoke(null, new object[] { noderef }); } setValue(prop, Activator.CreateInstance(GenericType, new object[] { value })); } } else { try { //Its a more complex type ( not generic but yes a object with properties and setter's) if (noderef.ChildNodes.Count > 0) { //Otherwise of arrays convert to XML to send var fromXMLMethods = typeof(Gale.Serialization).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); System.Reflection.MethodInfo fromXMLMethodInfo = fromXMLMethods.FirstOrDefault(mi => mi.Name == "FromXML" && mi.GetGenericArguments().Count() == 1 && mi.GetParameters()[0].ParameterType == typeof(XmlNode)); System.Reflection.MethodInfo method = fromXMLMethodInfo.MakeGenericMethod(new Type[] { propertyType }); var value = method.Invoke(null, new object[] { noderef }); setValue(prop, Convert.ChangeType(value, propertyType)); //try to set into the variable anyways , if throw error then throw invalid cast exception } else { setValue(prop, Convert.ChangeType(nodeValue, propertyType)); //try to set into the variable anyways , if throw error then throw invalid cast exception } } catch { //TODO: Perform this Section, To Support Non Primitive Object Type throw new Gale.Exception.GaleException("InvalidCastInXMLDeserialization", prop.Name); } } } } }); return((T)(Entity)); }
private static void PushTargetMethodInfo(ILGenerator IL, MethodBuilder generatedMethod, MethodInfo method) { if (method.IsGenericMethodDefinition) { // We want the generated code to load a MethodInfo instantiated with the // current generic type parameters. I.e.: // MethodInfo methodInfo = methodof(TheClass.TheMethod<T>(...) // // We need to instantiate the open generic method definition with the type // arguments from the generated method. Using the open method definition // directly works on .Net 2.0, which might be FW bug, but fails on 4.0. // // Equivalent pseudo-code: // MethodInfo mi = methodof(TheClass.TheMethod<>) // versus // MethodInfo mi = methodof(TheClass.TheMethod<T0>) var instantiatedMethod = method.MakeGenericMethod(generatedMethod.GetGenericArguments()); IL.Emit(OpCodes.Ldtoken, instantiatedMethod); } else { IL.Emit(OpCodes.Ldtoken, method); } System.Type declaringType = method.DeclaringType; if (declaringType.IsGenericType) { IL.Emit(OpCodes.Ldtoken, declaringType); IL.Emit(OpCodes.Call, getGenericMethodFromHandle); } else { IL.Emit(OpCodes.Call, getMethodFromHandle); } IL.Emit(OpCodes.Castclass, typeof(MethodInfo)); }
private void createReadWriteMethods() { // Retrieve DataStream Read method implementing a generic format taking the vertex Type readMethod = typeof(DataStream).GetMethods(BindingFlags.Instance | BindingFlags.Public).Where<MethodInfo>(m => m.IsGenericMethod && m.Name == "Read").FirstOrDefault(); // Build a method with the specific type argument you're interested in readMethod = readMethod.MakeGenericMethod(countType); // Retrieve DataStream Write method implementing a generic format taking the vertex Type writeMethod = typeof(DataStream).GetMethods(BindingFlags.Instance | BindingFlags.Public).Where<MethodInfo>(m => m.IsGenericMethod && m.Name == "Write").FirstOrDefault(); // Build a method with the specific type argument you're interested in writeMethod = writeMethod.MakeGenericMethod(countType); }
// cls = class type (such as typeof(JTokenExtensions)).. gentype = <T> parameter. then Invoke with return.Invoke(null,new Object[] { values..}) if static, null = instance if not public static MethodInfo CreateGeneric(Type cls, string methodname, Type gentype) { System.Reflection.MethodInfo method = cls.GetMethod(methodname, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); return(method.MakeGenericMethod(gentype)); }
private static MethodInfo ApplyTypeArgs(MethodInfo m, Type[] typeArgs) { if (typeArgs == null || typeArgs.Length == 0) { if (!m.IsGenericMethodDefinition) return m; } else { if (m.IsGenericMethodDefinition && m.GetGenericArguments().Length == typeArgs.Length) return m.MakeGenericMethod(typeArgs); } return null; }
protected MethodCallExpression ResolveNamedMethodCallExpression(string name, MethodInfo method, Type parameterType, ParameterExpression instance) { method = method.MakeGenericMethod(parameterType); return Expression.Call(instance, method, Expression.Constant(name)); }