System.Reflection.MethodInfo.MakeGenericMethod(params System.Type[])

Here are the examples of the csharp api System.Reflection.MethodInfo.MakeGenericMethod(params System.Type[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2053 Examples 7

19 View Source File : FSharpUtils.cs
License : MIT License
Project Creator : akaskela

public static ObjectConstructor<object> CreateMap(Type keyType, Type valueType)
        {
            MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator");

            MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType);

            return (ObjectConstructor<object>)creatorGeneric.Invoke(null, null);
        }

19 View Source File : FieldFactory.cs
License : MIT License
Project Creator : alelievr

public static VisualElement CreateField(Type fieldType, object value, Action< object > onValueChanged, string label)
		{
			if (typeof(Enum).IsreplacedignableFrom(fieldType))
				fieldType = typeof(Enum);

			VisualElement field = null;

			// Handle special cases here
			if (fieldType == typeof(LayerMask))
			{
				// LayerMasks inherit from INotifyValueChanged<int> instead of INotifyValueChanged<LayerMask>
				// so we can't register it inside our factory system :(
				var layerField = new LayerMaskField(label, ((LayerMask)value).value);
				layerField.RegisterValueChangedCallback(e => {
					onValueChanged(new LayerMask{ value = e.newValue});
				});

				field = layerField;
			}
			else
			{
				try
				{
					var createFieldSpecificMethod = createFieldMethod.MakeGenericMethod(fieldType);
					try
					{
						field = createFieldSpecificMethod.Invoke(null, new object[]{value, onValueChanged, label}) as VisualElement;
					} catch {}

					// handle the Object field case
					if (field == null && (value == null || value is UnityEngine.Object))
					{
						createFieldSpecificMethod = createFieldMethod.MakeGenericMethod(typeof(UnityEngine.Object));
						field = createFieldSpecificMethod.Invoke(null, new object[]{value, onValueChanged, label}) as VisualElement;
						if (field is ObjectField objField)
						{
							objField.objectType = fieldType;
							objField.value = value as UnityEngine.Object;
						}
					}
				}
				catch (Exception e)
				{
					Debug.LogError(e);
				}
			}

			return field;
		}

19 View Source File : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj

public RenderFragment CreateFormElement() => builder =>
        {
            if (FormColumnDefinition.Model.GetType() == typeof(ExpandoObject))
            {
                // Accesing a ExpandoObject requires to cast the model as a dictionary, so it's accesable by a key of type string
                var accessor = ((IDictionary<string, object>)FormColumnDefinition.Model);

                foreach (var key in accessor.Keys)
                {
                    // get the value of the object
                    var value = accessor[key];

                    // Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
                    MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferenceExpando), BindingFlags.NonPublic | BindingFlags.Instance);
                    MethodInfo genericMethod = method.MakeGenericMethod(value.GetType());
                    // Execute the method with the following parameters
                    genericMethod.Invoke(this, new object[] { accessor, key, builder, FormColumnDefinition });
                }
            }
            else // replacedume it's a regular clreplaced, could be tighter scoped
            {
                var propertyFormElement = FormColumnDefinition.Model.GetType().GetProperty(FormColumnDefinition.Name);
                // Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
                MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferencePoco), BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo genericMethod = method.MakeGenericMethod(propertyFormElement.PropertyType);
                // Execute the method with the following parameters
                genericMethod.Invoke(this, new object[] { FormColumnDefinition.Model, propertyFormElement, builder, FormColumnDefinition });
            }
        };

19 View Source File : CommandsNextExtension.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<object> ConvertArgument(string value, CommandContext ctx, Type type)
#pragma warning restore IDE1006 // Naming Styles
        {
            var m = this.ConvertGeneric.MakeGenericMethod(type);
            try
            {
                return await (m.Invoke(this, new object[] { value, ctx }) as Task<object>).ConfigureAwait(false);
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }

19 View Source File : LogEventTests.AppendWithFormat.cs
License : MIT License
Project Creator : Abc-Arbitrage

[TestCase(typeof(byte), "X4")]
        [TestCase(typeof(short), "X4")]
        [TestCase(typeof(int), "X")]
        [TestCase(typeof(long), "X")]
        [TestCase(typeof(float), "E")]
        [TestCase(typeof(double), "P3")]
        [TestCase(typeof(decimal), "E04")]
        [TestCase(typeof(Guid), "X")]
        [TestCase(typeof(DateTime), "yyyy-MM-dd")]
        [TestCase(typeof(TimeSpan), "g")]
        public void should_append_nullable_with_format(Type type, string format)
        {
            typeof(LogEventTests).GetMethod(nameof(should_append_nullable_with_format), BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(string) }, null)
                                 .MakeGenericMethod(type)
                                 .Invoke(this, new object[] { format });
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private object CallPrivateGenericMethod(Type typeOfT, string privateMethodName, object[] parameters)
        {
            var methodInfo = ((TypeInfo) typeof(TypeFuzzer)).DeclaredMethods.Single(m =>
                m.IsGenericMethod && m.IsPrivate && m.Name.Contains(privateMethodName));
            var generic = methodInfo.MakeGenericMethod(typeOfT);
            
            // private T GenerateInstanceOf<T>(int recursionLevel)
            var result = generic.Invoke(this, parameters);
            
            return result;
        }

19 View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari

(MethodBase method, bool boundToFieldOrProp) BindToMethod (Type type, string memberName, BindingFlags bindingFlags, Type[] typeArgs,
                                                                   ParameterModifier parameterModifiers, bool throwOnBadMethodOverload, ref object[] args)
        {
            int argCount = args.Length;
            var args2 = args;

            var matchingMember = GetTypeHierarchy (type).Select (SelectMethod).FirstOrDefault (x => x != null);
            if (matchingMember != null)
            {
                args = args2;
                return (matchingMember, true);
            }

            // If there's a field or property with that name, allow it to bind to that. It's possible that the field or
            // property could return a delegate type that can be invoked.
            return (null, GetFieldOrProperty (type, memberName, bindingFlags, false).MemberInfo != null);

            MethodBase SelectMethod (Type t)
            {
                MethodBase[] methods;

                // Find all the compatible methods on this type, i.e., the methods whose
                // (1) parameter count >= the argument count (the parameter count can be greater because we support optional parameters)
                // (2) type argument count matches the number of type args preplaceded in by the caller
                // (3) parameter types are preplaced-by-reference if specified by the caller
                methods = t
                    .GetMember (memberName, MemberTypes.Method, bindingFlags)
                    .OfType<MethodInfo> ()
                    .Where (m => m.GetParameters ().Length >= argCount && m.GetGenericArguments ().Length == typeArgs.Length)
                    .Where (m => IsByRefCompatible (m.GetParameters ()))
                    .Select (m => m.IsGenericMethod ? m.MakeGenericMethod (typeArgs) : m)
                    .ToArray ();

                if (methods.Length == 0) return null;

                // Use DefaultBinder to pick the correct overload. Note that it might give us back a different args array if
                // it needed to apply optional paarmeters.
                try
                {
                    return Type.DefaultBinder.BindToMethod (bindingFlags, methods, ref args2, null, null, null, out object state);
                }
                catch (MissingMethodException ex)
                {
                    if (!throwOnBadMethodOverload) return null;
                    throw ex.Wrap ($"Error binding type '{t}' to method '{memberName}'");
                }
            }

            bool IsByRefCompatible (ParameterInfo[] parameters)
            {
                for (int i = 0; i < argCount; i++)
                    if (parameters[i].ParameterType.IsByRef != parameterModifiers[i])
                        return false;

                // Any remaining parameters will be optional. Make sure that they're not preplaced-by-ref.
                for (int i = argCount; i < parameters.Length; i++)
                    if (parameters[i].ParameterType.IsByRef)
                        return false;

                return true;
            }
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildGenericIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type, Type genericKeyType, Type genericValueType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
            if (args.Length == 0)
            {
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictEmptyCtor));
                methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
            }
            else
            {
                DEBUG.replacedert(args.Length == 1);
                if (args[0].ParameterType == typeof(int))
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictCapacityCtor));
                    methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
                }
                else
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
                    methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                }
            }
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : TypeAdapter.cs
License : MIT License
Project Creator : alelievr

static void LoadAllAdapters()
        {
            foreach (Type type in AppDomain.CurrentDomain.GetAllTypes())
            {
                if (typeof(ITypeAdapter).IsreplacedignableFrom(type))
                {
                    if (type.IsAbstract)
                        continue;
                    
                    var adapter = Activator.CreateInstance(type) as ITypeAdapter;
                    if (adapter != null)
                    {
                        foreach (var types in adapter.GetIncompatibleTypes())
                        {
                            incompatibleTypes.Add((types.Item1, types.Item2));
                            incompatibleTypes.Add((types.Item2, types.Item1));
                        }
                    }
                    
                    foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
                    {
                        if (method.GetParameters().Length != 1)
                        {
                            Debug.LogError($"Ignoring convertion method {method} because it does not have exactly one parameter");
                            continue;
                        }
                        if (method.ReturnType == typeof(void))
                        {
                            Debug.LogError($"Ignoring convertion method {method} because it does not returns anything");
                            continue;
                        }
                        Type from = method.GetParameters()[0].ParameterType;
                        Type to = method.ReturnType;

                        try {

#if ENABLE_IL2CPP
                            // IL2CPP doesn't suport calling generic functions via reflection (AOT can't generate templated code)
                            Func<object, object> r = (object param) => { return (object)method.Invoke(null, new object[]{ param }); };
#else
                            MethodInfo genericHelper = typeof(TypeAdapter).GetMethod("ConvertTypeMethodHelper", 
                                BindingFlags.Static | BindingFlags.NonPublic);
                            
                            // Now supply the type arguments
                            MethodInfo constructedHelper = genericHelper.MakeGenericMethod(from, to);

                            object ret = constructedHelper.Invoke(null, new object[] {method});
                            var r = (Func<object, object>) ret;
#endif

                            adapters.Add((method.GetParameters()[0].ParameterType, method.ReturnType), r);
                            adapterMethods.Add((method.GetParameters()[0].ParameterType, method.ReturnType), method);
                        } catch (Exception e) {
                            Debug.LogError($"Failed to load the type convertion method: {method}\n{e}");
                        }
                    }
                }
            }

            // Ensure that the dictionary contains all the convertions in both ways
            // ex: float to vector but no vector to float
            foreach (var kp in adapters)
            {
                if (!adapters.ContainsKey((kp.Key.to, kp.Key.from)))
                    Debug.LogError($"Missing convertion method. There is one for {kp.Key.from} to {kp.Key.to} but not for {kp.Key.to} to {kp.Key.from}");
            }

            adaptersLoaded = true;
        }

19 View Source File : IFormatterResolver.cs
License : MIT License
Project Creator : 1996v

public static IBssomFormatter GetFormatterWithVerify(this IFormatterResolver resolver, Type type)
        {
            if (resolver is null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!FormatterGetters.TryGetValue(type, out Func<IFormatterResolver, IBssomFormatter> formatterGetter))
            {
                MethodInfo genericMethod = GetFormatterMethodInfo.MakeGenericMethod(type);
                ParameterExpression inputResolver = Expression.Parameter(typeof(IFormatterResolver), "inputResolver");
                formatterGetter = Expression.Lambda<Func<IFormatterResolver, IBssomFormatter>>(
                    Expression.Call(inputResolver, genericMethod), inputResolver).Compile();
                FormatterGetters.TryAdd(type, formatterGetter);
            }

            return formatterGetter(resolver);
        }

19 View Source File : TypeHelpers.cs
License : MIT License
Project Creator : adrianoc

public static MethodInfo ResolveGenericMethod(string replacedemblyName, string declaringTypeName, string methodName, BindingFlags bindingFlags, IEnumerable<string> typeArguments,
            IEnumerable<ParamData> paramTypes)
        {
            var containingreplacedembly = replacedembly.Load(replacedemblyName);
            var declaringType = containingreplacedembly.GetType(declaringTypeName);

            var typeArgumentsCount = typeArguments.Count();
            var methods = declaringType.GetMethods(bindingFlags)
                .Where(c => c.Name == methodName
                            && c.IsGenericMethodDefinition
                            && c.GetParameters().Length == paramTypes.Count()
                            && typeArgumentsCount == c.GetGenericArguments().Length);

            if (methods == null)
            {
                throw new MissingMethodException(declaringTypeName, methodName);
            }

            var paramTypesArray = paramTypes.ToArray();
            foreach (var mc in methods)
            {
                var parameters = mc.GetParameters();
                var found = true;

                for (var i = 0; i < parameters.Length; i++)
                {
                    if (!CompareParameters(parameters[i], paramTypesArray[i]))
                    {
                        found = false;
                        break;
                    }
                }

                if (found)
                {
                    return mc.MakeGenericMethod(typeArguments.Select(Type.GetType).ToArray());
                }
            }

            return null;
        }

19 View Source File : RoslynDiagnosticService.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static object GetDiagnosticServiceInstance(IComponentModel componentModel, Type diagnosticreplacedyzerServiceType)
		{
			Type componentModelType = componentModel.GetType();
			var getServiceMethodInfo = componentModelType.GetMethod(nameof(componentModel.GetService))
														?.MakeGenericMethod(diagnosticreplacedyzerServiceType);
			if (getServiceMethodInfo == null)
				return null;

			try
			{
				return getServiceMethodInfo.Invoke(componentModel, null);
			}
			catch (Exception e)
			{
				return null;
			}
		}

19 View Source File : QueryableExtension.cs
License : GNU General Public License v3.0
Project Creator : 2dust

static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc)
        {
            string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";

            var memberProp = typeof(T).GetProperty(propertyName);

            var method = typeof(QueryableExtension).GetMethod(methodname)
                                       .MakeGenericMethod(typeof(T), memberProp.PropertyType);

            return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp });
        }

19 View Source File : AsyncEnumerableTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Fact]
        public void NullChecks()
        {
            foreach (var m2 in typeof(AsyncEnumerable).GetMethods())
            {
                if (m2.IsStatic && m2.IsPublic)
                {
                    MethodInfo m;

                    if (m2.IsGenericMethod)
                    {
                        var argumentTypes = m2.GetGenericArguments();
                        var callArgumentTypes = new Type[argumentTypes.Length];
                        
                        for (var i = 0; i < argumentTypes.Length; i++)
                        {
                            var argumentType = argumentTypes[i];

                            var argumentConstraint = argumentType.GetGenericParameterConstraints();

                            if (argumentConstraint.Length == 0)
                            {
                                callArgumentTypes[i] = typeof(int);
                            } else
                            if (argumentConstraint[0].Name.Contains("ICollection"))
                            {
                                callArgumentTypes[i] = typeof(ICollection<int>);
                            }
                            else
                            {
                                replacedert.False(true, "Method generic parameter default missing: " + argumentType);
                            }
                        }

                        m = m2.MakeGenericMethod(callArgumentTypes);
                    }
                    else
                    {
                        m = m2;
                    }

                    var args = m.GetParameters();

                    for (var i = 0; i < args.Length; i++)
                    {
                        var arg = args[i];

                        if ((arg.ParameterType.IsClreplaced || arg.ParameterType.IsInterface) && !arg.HasDefaultValue)
                        {
                            var pars = new object[args.Length];
                            for (var j = 0; j < args.Length; j++)
                            {
                                if (j != i)
                                {
                                    pars[j] = GetDefault(args[j].ParameterType, m);
                                }
                            }

                            var thrown = false;
                            try
                            {
                                m.Invoke(null, pars);
                            }
                            catch (TargetInvocationException ex)
                            {
                                if (ex.InnerException is ArgumentNullException)
                                {
                                    thrown = true;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            if (!thrown)
                            {
                                replacedert.False(true, "Method " + m.Name + " argument " + arg.Name + " should have thrown!");
                            }
                        }
                    }
                }
            }
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
        {
            /*
               if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
                    return default;
               context.option.Security.DepthStep(ref reader);
               reader.SkipVariableNumber();
               int len = reader.ReadVariableNumber();
               T t = new T(len);
               Fill<T>(ref t,ref reader,ref context,len);
               context.Depth--;
               return t;  
            */

            bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
            Type t = typeof(T);
            List<Expression> ary = new List<Expression>(7);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");

            if (isArray1Type)
            {
                if (isNativeType)
                {
                    //if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
                else
                {
                    //if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
            }
            else
            {
                //if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
                //      goto label;
                ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
            }

            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);

            //reader.SkipVariableNumber();
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);

            //int len = reader.ReadVariableNumber();
            ParameterExpression len = Expression.Variable(typeof(int));
            ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));

            //T t = ctor(len);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(len)));
            MethodInfo method = null;
            if (isImplGenerICollec == false)
            {
                //IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
                method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
            }
            else
            {
                if (isArray1Type)
                {
                    //IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
                    method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
                }
                else
                {
                    //IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
                    method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
                }
            }

            ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { instance, len }, ary);
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();


        }

19 View Source File : ImmutableCollectionsUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator)
        {
            if (underlyingType.IsGenericType())
            {
                Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition();
                string name = underlyingTypeDefinition.FullName;

                ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name);
                if (definition != null)
                {
                    Type createdTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.CreatedTypeName);
                    Type builderTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.BuilderTypeName);

                    if (createdTypeDefinition != null && builderTypeDefinition != null)
                    {
                        MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m =>
                        {
                            ParameterInfo[] parameters = m.GetParameters();

                            return m.Name == "CreateRange" && parameters.Length == 1 && parameters[0].ParameterType.IsGenericType() && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
                        });
                        if (mb != null)
                        {
                            createdType = createdTypeDefinition.MakeGenericType(keyItemType, valueItemType);
                            MethodInfo method = mb.MakeGenericMethod(keyItemType, valueItemType);
                            parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method);
                            return true;
                        }
                    }
                }
            }

            createdType = null;
            parameterizedCreator = null;
            return false;
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapVector(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Vector<>));
            var vectorT = valueType.GetGenericArguments().First();

            _writeVectorTMethod.MakeGenericMethod(vectorT).Invoke(this, new object[] { value, context });
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
            this IQueryable<TOuter> outer,
            IQueryable<TInner> inner,
            Expression<Func<TOuter, TKey>> outerKeySelector,
            Expression<Func<TInner, TKey>> innerKeySelector,
            Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {
            MethodInfo groupJoin = typeof(Queryable).GetMethods()
                                                     .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                     .MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(LeftJoinIntermediate<TOuter, TInner>));
            MethodInfo selectMany = typeof(Queryable).GetMethods()
                                                      .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                      .MakeGenericMethod(typeof(LeftJoinIntermediate<TOuter, TInner>), typeof(TInner), typeof(TResult));

            var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                          ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> { OneOuter = oneOuter, ManyInners = manyInners });

            MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

            var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                               (t => t.ManyInners.DefaultIfEmpty());

            ParameterExpression paramUser = resultSelector.Parameters.First();

            ParameterExpression paramNew = Expression.Parameter(typeof(LeftJoinIntermediate<TOuter, TInner>), "t");
            MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

            LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body) ?? throw new InvalidOperationException(), paramNew, resultSelector.Parameters.Skip(1).First());

            MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

            return outer.Provider.CreateQuery<TResult>(exprSelectMany);
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_GetFormatterWithVerify(Expression resolver, Type formatterType)
        {
            return Expression.Call(null, typeof(FormatterResolverExtensions).GetMethod(nameof(FormatterResolverExtensions.GetFormatterWithVerify), new Type[] { typeof(IFormatterResolver) }).MakeGenericMethod(formatterType), resolver);
        }

19 View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr

object GetInputFieldValue(FieldInfo info)
		{
			// Warning: Keep in sync with FieldFactory CreateField
			var fieldType = info.FieldType.IsSubclreplacedOf(typeof(UnityEngine.Object)) ? typeof(UnityEngine.Object) : info.FieldType;
			var genericUpdate = specificGetValue.MakeGenericMethod(fieldType);

			return genericUpdate.Invoke(this, new object[]{info});
		}

19 View Source File : UnmanagedCache.cs
License : MIT License
Project Creator : Abc-Arbitrage

internal static void Register(Type unmanagedType)
        {
            if (unmanagedType == null)
                throw new ArgumentNullException(nameof(unmanagedType));

            if (!typeof(IStringFormattable).IsreplacedignableFrom(unmanagedType))
                throw new ArgumentException($"Not an {nameof(IStringFormattable)} type: {unmanagedType}");

            if (!TypeUtil.GetIsUnmanagedSlow(unmanagedType))
                throw new ArgumentException($"Not an unmanaged type: {unmanagedType}");

            _registerMethod.MakeGenericMethod(unmanagedType).Invoke(null, null);
        }

19 View Source File : LogEventTests.Append.cs
License : MIT License
Project Creator : Abc-Arbitrage

[TestCase(typeof(bool))]
        [TestCase(typeof(byte))]
        [TestCase(typeof(char))]
        [TestCase(typeof(short))]
        [TestCase(typeof(int))]
        [TestCase(typeof(long))]
        [TestCase(typeof(float))]
        [TestCase(typeof(double))]
        [TestCase(typeof(decimal))]
        [TestCase(typeof(Guid))]
        [TestCase(typeof(DateTime))]
        [TestCase(typeof(TimeSpan))]
        public void should_append_nullable(Type type)
        {
            typeof(LogEventTests).GetMethod(nameof(should_append_nullable), BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null)
                                 .MakeGenericMethod(type)
                                 .Invoke(this, new object[0]);
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression AsPointerExpression(Expression instance)
        {
            var asPointerMethodType = typeof(ExpressionTreeAux).GetMethod(nameof(ExpressionTreeAux.AsPointer)).MakeGenericMethod(instance.Type);
            return Expression.Call(null, asPointerMethodType, instance);
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

private static Delegate GetSerializerFor([NotNull] Type type)
		{
			if (type == null) throw new ArgumentNullException("type");

			if (type == typeof(object))
			{ // return a generic serializer that will inspect the runtime type of the object
				return new Encoder<object>(FdbTuplePackers.SerializeObjectTo);
			}

			var typeArgs = new[] { typeof(TupleWriter).MakeByRefType(), type };
			var method = typeof(FdbTuplePackers).GetMethod("SerializeTo", BindingFlags.Static | BindingFlags.Public, null, typeArgs, null);
			if (method != null)
			{ // we have a direct serializer
				return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
			}

			// maybe if it is a tuple ?
			if (typeof(IFdbTuple).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeTupleTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(type).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(ITupleFormattable).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFormattableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(IFdbKey).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFdbKeyTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			var nullableType = Nullable.GetUnderlyingType(type);
			if (nullableType != null)
			{ // nullable types can reuse the underlying type serializer
				method = typeof(FdbTuplePackers).GetMethod("SerializeNullableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(nullableType).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			// TODO: look for a static SerializeTo(BWB, T) method on the type itself ?

			// no luck..
			return null;
		}

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

public override IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];

			var tb = _orm.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
			if (tb == null) return null;

			object repos = _repos;
			if (enreplacedyType != _repos.EnreplacedyType) {
				repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(enreplacedyType, typeof(int)), _repos.Orm);
				(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
				GetRepositoryDbField(enreplacedyType).SetValue(repos, this);

				typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EnreplacedyType)
					.Invoke(null, new object[] { repos, _repos });
			}

			var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(enreplacedyType), repos) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : NodeContainerSerializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public INodeContainer DeSerialize(ISerializedObject<INodeContainer> serialized, ISerializer serializer, object deserializationContext)
        {
            if (serialized is not SerializedNodeContainer serializedNodeContainer)
            {
                throw new ArgumentException("Can only deserialize objects of type SerializedNodeContainer", nameof(serialized));
            }

            if (deserializationContext is not IAdvancedScript advancedScript)
            {
                throw new ArgumentException("NodeContainerSerializer needs a context of type IAdvancedScript to work");
            }

            INode coreNode;
            INodeContainer output;
            Type coreNodeType = _instance.GetNodeType(serializedNodeContainer.CoreNodeName, serializedNodeContainer.Plugin);
            if (coreNodeType == typeof(InputNode))
            {
                coreNode = advancedScript.Inputs[serializedNodeContainer.Name];
                output = (INodeContainer)_getNodeMethod.MakeGenericMethod(coreNodeType).Invoke(_nodeFactory, new object[] { coreNode, serializedNodeContainer.Guid });
            }
            else
            {
                coreNode = (INode)Activator.CreateInstance(coreNodeType);
                MethodInfo GetNodeMethod = _getNodeMethod.MakeGenericMethod(coreNodeType);
                output = (INodeContainer)GetNodeMethod.Invoke(_nodeFactory, new object[] { coreNode, serializedNodeContainer.Guid });
                coreNode.GetNameLabel().Name.Value = serializedNodeContainer.Name;
                foreach ((object serializedComponent, INodeComponent component) in serializedNodeContainer.SerializedComponents.Zip(coreNode.Fields))
                {
                    component.ParentNode = coreNode;
                    DeserializeNodeComponentTo(serializedComponent, component, serializer);
                }
            }
            output.Location.X = serializedNodeContainer.X;
            output.Location.Y = serializedNodeContainer.Y;
            return output;
        }

19 View Source File : AopCacheAttribute.cs
License : MIT License
Project Creator : ad313

private async Task<object> GetCahceValue(string key, Type type, AspectContext context)
        {
            //从缓存取值
            var cacheValue = await CacheProvider.Get(key, type);
            if (cacheValue != null)
            {
                context.ReturnValue = context.IsAsync()
                    ? TaskResultMethod.MakeGenericMethod(type).Invoke(null, new object[] { cacheValue })
                    : cacheValue;
            }
            return cacheValue;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : 2881099

public static MethodInfo GetLinqContains(Type genericType) {
			return _dicGetLinqContains.GetOrAdd(genericType, gt => {
				var methods = _dicMethods.GetOrAdd(typeof(Enumerable), gt2 => gt2.GetMethods());
				var method = methods.Where(a => a.Name == "Contains" && a.GetParameters().Length == 2).FirstOrDefault();
				return method?.MakeGenericMethod(gt);
			});
		}

19 View Source File : MongoDatabaseExtension.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static object GetCollection(this IMongoDatabase database, Type enreplacedyType)
        {
            var genericGetCollectionMethod = _getCollectionMethod.MakeGenericMethod(enreplacedyType);
            return genericGetCollectionMethod.Invoke(database, new object [] { enreplacedyType.Name, _settings });
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            if (type.IsGenericType == false)
            {
                DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
                //itemType is Object, Array2
                if (type == typeof(IList))
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                Type genericTypeDefine = type.GetGenericTypeDefinition();
                DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));

                if (Array1FormatterHelper.IsArray1Type(elementType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
                    }
                    else
                    {
                        Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
                        FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
                        MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
                        TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
                }
                else
                {
                    if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                }
            }

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : OptionsBuilder.cs
License : MIT License
Project Creator : aivascu

public virtual object Build(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!typeof(DbContext).IsreplacedignableFrom(type) || type.IsAbstract)
            {
                throw new ArgumentException(Invariant($"The context type should be a non-abstract clreplaced inherited from {typeof(DbContext)}"), nameof(type));
            }

            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);

            var genericConfigureMethod = Array
                .Find(methods, m => m.Name == nameof(Build) && m.IsGenericMethodDefinition)
                .MakeGenericMethod(type);

            return genericConfigureMethod.Invoke(this, Array.Empty<object>());
        }

19 View Source File : ImmutableCollectionDecorator.cs
License : MIT License
Project Creator : 404Lcc

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null) return false;
#if WINRT || COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if(!declaredTypeInfo.IsGenericType) return false;

#if WINRT || COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if WINRT || PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : FSharpUtils.cs
License : MIT License
Project Creator : akaskela

public static ObjectConstructor<object> CreateSeq(Type t)
        {
            MethodInfo seqType = _ofSeq.MakeGenericMethod(t);

            return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType);
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_MapFormatterHelper_Deserialize(Type keyType, Type valueType)
        {
            return Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.Deserialize)).MakeGenericMethod(keyType, valueType), Par_Reader, Par_DeserializeContext);
        }

19 View Source File : ImmutableCollectionsUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator)
        {
            if (underlyingType.IsGenericType())
            {
                Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition();
                string name = underlyingTypeDefinition.FullName;

                ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name);
                if (definition != null)
                {
                    Type createdTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.CreatedTypeName);
                    Type builderTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.BuilderTypeName);

                    if (createdTypeDefinition != null && builderTypeDefinition != null)
                    {
                        MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1);
                        if (mb != null)
                        {
                            createdType = createdTypeDefinition.MakeGenericType(collectionItemType);
                            MethodInfo method = mb.MakeGenericMethod(collectionItemType);
                            parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method);
                            return true;
                        }
                    }
                }
            }

            createdType = null;
            parameterizedCreator = null;
            return false;
        }

19 View Source File : Visitor.Expressions.cs
License : MIT License
Project Creator : 71

public override Expression VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            if (node.Expression is MemberAccessExpressionSyntax access)
            {
                var syntaxArgs = node.ArgumentList.Arguments;
                Expression[] arguments = new Expression[syntaxArgs.Count];

                Expression expr = access.Expression.Accept(this);

                GenericNameSyntax generic = access.Name as GenericNameSyntax;
                bool isGeneric = generic != null;
                Type[] genericTypes = null;
                string name = access.Name.Identifier.Text;
                bool isStatic = expr is TypeExpression;

                bool FindGenericMethod(MethodInfo match)
                {
                    if (genericTypes == null)
                        genericTypes = generic.TypeArgumentList.Arguments.Select(AsType);

                    return match.IsGenericMethod
                           && match.IsStatic == isStatic
                           && match.GetParameters().Length == arguments.Length
                           && match.GetGenericArguments().Length == genericTypes.Length;
                }

                bool FindMethod(MethodInfo match)
                {
                    return match.IsStatic == isStatic
                        && !match.IsGenericMethod
                        && match.GetParameters().Length == arguments.Length;
                }

                MethodInfo method = isGeneric
                    ? expr.Type.GetTypeInfo()
                          .GetMethods(name).First(FindGenericMethod)
                    : expr.Type.GetTypeInfo()
                          .GetMethods(name).First(FindMethod);

                if (isGeneric)
                    method = method.MakeGenericMethod(genericTypes);

                ParameterInfo[] parameters = method.GetParameters();

                for (int i = 0; i < arguments.Length; i++)
                {
                    arguments[i] = Convert(syntaxArgs[i].Accept(this), parameters[i].ParameterType);
                }

                return Expression.Call(expr is TypeExpression ? null : expr, method, arguments);
            }

            return node.Expression.Accept(this);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

void DrawBuffer(Vector2 position)
    {
        if (registry.Count > 256)
        {
            DrawString(position, $"TOO MUCH DATA TO RENDER! ({registry.Count} enreplacedies)\ntimings:\n{String.Join("\n", timings)}", Color.Red);

            return;
        }

        var buffers = registry.__GetBuffers();

        var entVals = position + Vector2.UnitY * 0;
        var keysPos = position + Vector2.UnitY * 28;
        var k2iPos = position + Vector2.UnitY * 64;

        int hspc = 28;

        DrawString(entVals+Vector2.UnitY*-6, "data:", Color.Gray);
        DrawString(entVals+Vector2.UnitY*0 , "tags:", Color.Gray);
        DrawString(entVals+Vector2.UnitY*6 , "dens:", Color.Gray);
        DrawString(entVals+Vector2.UnitY*12, "spar:", Color.Gray);
        for (var i = 0; i < registry.Count; i++)
        {
            var val = buffers.data[i];

            var entuid = buffers.i2k[i];

            Vector2 pos = ind2pos(entVals + Vector2.UnitX * hspc, i);

            DrawString(pos+Vector2.UnitY*0 , mask2str(val.Tags), Color.LightBlue);
            DrawString(pos+Vector2.UnitY*6 , mask2str(val.FlagsDense), Color.Gold);
            DrawString(pos+Vector2.UnitY*12,mask2str(val.FlagsSparse), Color.LightSeaGreen);

            if (CurrentDbgLoopEntry != null && CurrentDbgLoopEntry.Value.entIdx == i)
                sb.Draw(px, new Rectangle((int)pos.X, (int)pos.Y, 20, 30), new Color(Color.Red, 0.5f));

            if (imbutton(pos + Vector2.UnitY * -10, "REMOV"))
            {
                registry.DeleteEnreplacedy(buffers.i2k[i]);
                return;
            }

            int c2 = 2;
            foreach (ComponentBufferBase buffer in registry.GetDebugComponentBufferBases())
            {

                var hascomp = buffer.HasComponentSlow(ref val);

                string compNameStr = buffer.GetType().GenericTypeArguments[0].Name;
                var comptype = Type.GetType(compNameStr, false, true);
                MethodInfo methodInfo = GetType().GetMethod("AddComp");
                MethodInfo genericMethod = methodInfo.MakeGenericMethod(comptype);

                if (imbutton(pos+Vector2.UnitY * -10 * c2, (hascomp ? "-" : "+")+compNameStr.Substring(0, 3)))
                {
                    if (hascomp)
                        genericMethod.Invoke(this, new object[] {entuid, true});
                    else
                        genericMethod.Invoke(this, new object[] {entuid, false});
                }

                c2++;
            }
            
        }
        
        var keysRenderPos = RenderKeys(keysPos, buffers.i2k, "UIDs", registry.Count, hspc, Color.Red);
        RenderDenseMap(k2iPos, buffers.k2i, hspc, keysRenderPos);

        var sp = k2iPos + Vector2.UnitY * 64;

        int c = 0;
        var cols = new[]{Color.Red, Color.Yellow, Color.Lime, Color.HotPink, Color.CadetBlue, };

        foreach (ComponentBufferBase buffer in registry.GetDebugComponentBufferBases())
        {

            string compNameStr = buffer.GetType().GenericTypeArguments[0].Name;
            var comptype = Type.GetType(compNameStr, false, true);

            string bt = buffer.Sparse ? "Sparse" : "Dense";

            DrawString(sp, $"{compNameStr} Buffer (Type: {bt}, Count: {buffer.ComponentCount})", Color.Orange);

            DrawString(sp + Vector2.UnitY * 6, $"flag: {mask2str(buffer.Matcher.Flag)} {bt[0]}", buffer.Sparse ? Color.LightSeaGreen : Color.Gold);

            var bd = buffer.GetDebugFlagAndEntIdxs();
            var keysps = RenderKeys(sp + Vector2.UnitY * 16, bd.endIdxs, "enti", buffer.ComponentCount, hspc, cols[c], keysPos);

            if (CurrentDbgLoopEntry != null)
                if (CurrentDbgLoopEntry.Value.buffersIndices.TryGetValue(buffer, out int indexInThisBuffer))
                    sb.Draw(px, new Rectangle((int) sp.X + 28 + 28*indexInThisBuffer, (int) sp.Y+28, 20, 8), new Color(Color.Yellow, 1f));

            //buffer.GetDebugIdxFromKey()

            if (!buffer.Sparse)
            {
                GetType().GetMethod("RenderCompBufDense").MakeGenericMethod(comptype)
                    .Invoke(this, new object[] { sp + Vector2.UnitY * 48, buffer, keysps});
            }
            else
            {
                GetType().GetMethod("RenderCompBufSparse").MakeGenericMethod(comptype)
                    .Invoke(this, new object[] { sp + Vector2.UnitY * 48, buffer, keysps});
            }

            sp += Vector2.UnitY*96;
            c++;
        }

        if (debugLoopQueue_.Count > 0)
        {
            ctr++;
            if (ctr > 3)
            {
                debugLoopQueue_.Dequeue();
                ctr = 0;
            }
        }
    }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildGenericIDictionaryInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type genericTypeDefine, Type genericKeyType, Type genericValueType)
        {
            DEBUG.replacedert(genericTypeDefine == typeof(IDictionary<,>) || genericTypeDefine == typeof(IReadOnlyDictionary<,>));

            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            if (genericTypeDefine == typeof(IDictionary<,>))
            {
                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.GenericDictionaryDeserialize), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
            }
            else
            {
                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.ReadOnlyGenericDictionaryDeserialize), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
            }

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));


            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : TypeRegister.cs
License : MIT License
Project Creator : Albeoris

private Int32 RegisterTypes(replacedembly replacedembly, MethodInfo registrator)
        {
            Int32 count = 0;
            var parameters = new object[0];

            foreach (Type type in replacedembly.GetTypes())
            {
                if (!IsImportableType(type))
                    continue;

                MethodInfo genericMethod = registrator.MakeGenericMethod(type);
                genericMethod.Invoke(null, parameters);
                count++;
            }

            return count;
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapDictionary(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Amf3Dictionary<,>));
            var tKey = valueType.GetGenericArguments().First();
            var tValue = valueType.GetGenericArguments().Last();

            _writeDictionaryTMethod.MakeGenericMethod(tKey, tValue).Invoke(this, new object[] { value, context });
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrCollectionAnyEqual<TEnreplacedy, TValue, TMemberValue>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, IEnumerable<TValue>>> selector,
            Expression<Func<TValue, TMemberValue>> memberSelector,
            IEnumerable<TMemberValue> values
            )
        {
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression selectorParameter = selector.Parameters.Single();
            ParameterExpression memberParameter = memberSelector.Parameters.Single();
            var methodInfo = GetEnumerableMethod("Any", 2).MakeGenericMethod(typeof(TValue));
            var anyExpressions = values.Select(value =>
                    (Expression)Expression.Call(null,
                                                methodInfo,
                                                selector.Body,
                                                Expression.Lambda<Func<TValue, bool>>(Expression.Equal(memberSelector.Body,
                                                                                                       Expression.Constant(value, typeof(TMemberValue))),
                                                                                                       memberParameter
                                                                                                       )
                                                )
                );
            Expression body = anyExpressions.Aggregate((acreplacedulate, any) => Expression.Or(acreplacedulate, any));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, selectorParameter));
        }

19 View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade

public static ref T AsRef<T>(IntPtr value) {
            Delegate cached;
            lock (_AsRefCache)
                _AsRefCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return ref (cached as _AsRef<T>)(value);

            if (_AsRefHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsRefHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(module.TypeSystem.Int32)));
                    method.Body.Variables.Add(new(new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Stloc_0);
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsRefHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsRef<T> generated = _AsRefHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsRef<T>>() as _AsRef<T>;
            lock (_AsRefCache)
                _AsRefCache[typeof(T)] = generated;
            return ref generated(value);
        }

19 View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr

void UpdateOtherFieldValue(FieldInfo info, object newValue)
		{
			// Warning: Keep in sync with FieldFactory CreateField
			var fieldType = info.FieldType.IsSubclreplacedOf(typeof(UnityEngine.Object)) ? typeof(UnityEngine.Object) : info.FieldType;
			var genericUpdate = specificUpdateOtherFieldValue.MakeGenericMethod(fieldType);

			genericUpdate.Invoke(this, new object[]{info, newValue});
		}

19 View Source File : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj

public RenderFragment CreateFormElement() => builder =>
        {
            if (FormColumnDefinition.Model.GetType() == typeof(ExpandoObject))
            {
                // Accesing a ExpandoObject requires to cast the model as a dictionary, so it's accesable by a key of type string
                var accessor = ((IDictionary<string, object>)FormColumnDefinition.Model);

                foreach (var key in accessor.Keys)
                {
                    // get the value of the object
                    var value = accessor[key];

                    // Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
                    MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferenceExpando), BindingFlags.NonPublic | BindingFlags.Instance);
                    MethodInfo genericMethod = method.MakeGenericMethod(value.GetType());
                    // Execute the method with the following parameters
                    genericMethod.Invoke(this, new object[] { accessor, key, builder, FormColumnDefinition });
                }
            }
            else // replacedume it's a regular clreplaced, could be tighter scoped
            {
                var propertyFormElement = FormColumnDefinition.Model.GetType().GetProperty(FormColumnDefinition.Name);
                // Get the generic CreateFormComponent and set the property type of the model and the elementType that is rendered
                MethodInfo method = typeof(VxFormColumnBase).GetMethod(nameof(VxFormColumnBase.CreateFormElementReferencePoco), BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo genericMethod = method.MakeGenericMethod(propertyFormElement.PropertyType);
                // Execute the method with the following parameters
                genericMethod.Invoke(this, new object[] { FormColumnDefinition.Model, propertyFormElement, builder, FormColumnDefinition });
            }
        };

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
        {
            /*
               var map = MapFormatterHelper.Deserialize(ref reader,ref context);
               if (map == null)
                   return null;
               context.option.Security.DepthStep(ref reader);
               T t = new T();/new T(map.Count)
               Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
               reader = map.Reader; context = map.Context; 
               reader.Seek(map.EndPos);
               context.Depth--;
               return t;  
            */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = ctor(map.Count);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
            //MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade

public static IntPtr AsPointer<T>(ref T value) {
            Delegate cached;
            lock (_AsPointerCache)
                _AsPointerCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return (cached as _AsPointer<T>)(ref value);

            if (_AsPointerHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsPointerHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Conv_U);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsPointerHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsPointer<T> generated = _AsPointerHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsPointer<T>>() as _AsPointer<T>;
            lock (_AsPointerCache)
                _AsPointerCache[typeof(T)] = generated;
            return generated(ref value);
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public MethodInfo FindConvertMethod(Type csharpType, Type dbType)
        {
            if (GetUnderlyingType(dbType) == typeof(bool) || GetUnderlyingType(csharpType) == typeof(bool))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToBooleanMethod : MemberMapperMethod.ToBooleanNullableMethod;
            }
            if (GetUnderlyingType(csharpType).IsEnum)
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToEnumMethod.MakeGenericMethod(csharpType) : MemberMapperMethod.ToEnumNullableMethod.MakeGenericMethod(GetUnderlyingType(csharpType));
            }
            if (GetUnderlyingType(dbType) == typeof(char) || GetUnderlyingType(csharpType) == typeof(char))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToCharMethod : MemberMapperMethod.ToCharNullableMethod;
            }
            if (csharpType == typeof(string))
            {
                return MemberMapperMethod.ToStringMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(Guid) || GetUnderlyingType(csharpType) == typeof(Guid))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToGuidMethod : MemberMapperMethod.ToGuidNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(DateTime) || GetUnderlyingType(csharpType) == typeof(DateTime))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDateTimeMethod : MemberMapperMethod.ToDateTimeNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(byte) || GetUnderlyingType(dbType) == typeof(sbyte) || GetUnderlyingType(csharpType) == typeof(byte) || GetUnderlyingType(csharpType) == typeof(sbyte))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToByteMethod : MemberMapperMethod.ToByteNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(short) || GetUnderlyingType(dbType) == typeof(ushort) || GetUnderlyingType(csharpType) == typeof(short) || GetUnderlyingType(csharpType) == typeof(ushort))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn16Method : MemberMapperMethod.ToIn16NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(int) || GetUnderlyingType(dbType) == typeof(uint) || GetUnderlyingType(csharpType) == typeof(int) || GetUnderlyingType(csharpType) == typeof(uint))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn32Method : MemberMapperMethod.ToIn32NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(long) || GetUnderlyingType(dbType) == typeof(long) || GetUnderlyingType(csharpType) == typeof(long) || GetUnderlyingType(csharpType) == typeof(ulong))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn64Method : MemberMapperMethod.ToIn64NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(float) || GetUnderlyingType(csharpType) == typeof(float))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToFloatMethod : MemberMapperMethod.ToFloatNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(double) || GetUnderlyingType(csharpType) == typeof(double))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDoubleMethod : MemberMapperMethod.ToDoubleNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(decimal) || GetUnderlyingType(csharpType) == typeof(decimal))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDecimalMethod : MemberMapperMethod.ToDecimalNullableMethod;
            }
            return !IsNullableType(csharpType) ? MemberMapperMethod.ToObjectMethod.MakeGenericMethod(csharpType) : MemberMapperMethod.ToObjectNullableMethod.MakeGenericMethod(Nullable.GetUnderlyingType(GetUnderlyingType(csharpType)));
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionImplementationType(DynamicFormatterreplacedembly replacedembly, Type type, ConstructorInfo constructor,
                     Type itemType,
                     bool isImplGenerIList, bool IsImplIList, bool isImplGenerICollec, bool isImplIReadOnlyList)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            if (itemType == typeof(object))
            {
                //itemType is Object, Array2
                if (IsImplIList)
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (Array1FormatterHelper.IsArray1Type(itemType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));
                }
                else
                {
                    if (isImplGenerIList || isImplIReadOnlyList)
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                }
            }

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            if (args.Length == 1 && args[0].ParameterType != typeof(int))
            {
                //new T(IEnumerable t)
                Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateInjectCtor));
                methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (itemType == typeof(DateTime))//DateTime需要特殊处理,因为要处理Standrand和Native
                {
                    Type dtCollBuilder = typeof(DateTimeCollectionDeserializeBuilder<>).MakeGenericType(type);
                    MethodInfo methodinfo = dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.ConstructorInit));
                    methodinfo.Invoke(null, new object[] { constructor });

                    TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.Deserialize)));
                }
                else
                {
                    Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                    if (args.Length == 0)
                    {
                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithEmptyCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    else
                    {
                        DEBUG.replacedert(args.Length == 1 && args[0].ParameterType == typeof(int));

                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithCapacityCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
                }
            }
            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : SqlServerAsOfQueryableExtensions.cs
License : MIT License
Project Creator : Adam-Langley

public static IQueryable<TEnreplacedy> AsOf<TEnreplacedy>(this IQueryable<TEnreplacedy> source, DateTime date) where TEnreplacedy : clreplaced
        {
            return
              source.Provider is EnreplacedyQueryProvider
                ? source.Provider.CreateQuery<TEnreplacedy>(
                  Expression.Call(
                    instance: null,
                    method: AsOfMethodInfo.MakeGenericMethod(typeof(TEnreplacedy)),
                    arg0: source.Expression,
                    arg1: Expression.Constant(date)))
                : source;
        }

See More Examples