Exemplo n.º 1
0
        private static async ValueTask <TResult> ExecuteAsync <TSource, TResult>(System.Reflection.MethodInfo method, IQueryable <TSource> source, IEnumerable <object?> args, CancellationToken cancellation)
        {
            source.AssertNotNull(nameof(source));

            if (method.IsGenericMethodDefinition)
            {
                var genericArgumentCount = method.GetGenericArguments().Length;
                if (genericArgumentCount > 2)
                {
                    throw new RemoteLinqException("Implementation error: expected closed generic method definition.");
                }

                method = genericArgumentCount == 2
                    ? method.MakeGenericMethod(typeof(TSource), typeof(TResult))
                    : method.MakeGenericMethod(typeof(TSource));
            }

            var arguments = new[] { source.Expression }
            .Concat(args.Select(x => x is Expression exp ? (Expression)Expression.Quote(exp) : Expression.Constant(x)))
            .ToArray();
            var methodCallExpression = Expression.Call(method, arguments);

            if (source.Provider is IAsyncRemoteQueryProvider asyncQueryableProvider)
            {
                return(await asyncQueryableProvider.ExecuteAsync <TResult>(methodCallExpression, cancellation).ConfigureAwait(false));
            }

            return(source.Provider.Execute <TResult>(methodCallExpression));
        }
Exemplo n.º 2
0
        } // End Function MapJTokenTypeToDotNet

        private static object GetValue(Newtonsoft.Json.Linq.JToken value, System.Type t)
        {
            // string foo1 = value.ToString();
            // string foo = value.ToObject<string>();
            // int bar = value.ToObject<int>();

            // System.Reflection.MethodInfo method = GetToObjectMethod();
            System.Reflection.MethodInfo generic = s_ToObjectMethodInfo.MakeGenericMethod(t);
            return(generic.Invoke(value, null));
        } // End Function GetValue
Exemplo n.º 3
0
 public TestCase(System.Reflection.MethodInfo methodInfo, object[] args) : base(MethodHelper.GetDisplayName(methodInfo, args))
 {
     this.methodInfo = methodInfo.IsGenericMethod ?
                       methodInfo.MakeGenericMethod(args.Select(arg => arg.GetType()).ToArray()) :
                       methodInfo;
     this.arguments = args;
 }
        public static T ToEarlyBoundEntity <T>(this T ent) where T : Microsoft.Xrm.Sdk.Entity
        {
            if (ent.GetType().BaseType == typeof(Microsoft.Xrm.Sdk.Entity))
            {
                return(ent);
            }

            if (TO_ENT_GENS.ContainsKey(ent.LogicalName))
            {
                return(TO_ENT_GENS[ent.LogicalName].Invoke(ent, new object[0]) as T);
            }

            if (!entittypes.ContainsKey(ent.LogicalName))
            {
                var enttype = Reflection.Types.Instance.EntityTypeFor(ent.LogicalName);
                if (enttype != null)
                {
                    entittypes[ent.LogicalName] = enttype;
                    return(ToEarlyBoundEntity(ent));
                }
                throw new Exceptions.UnknownEntityTypeException(ent.LogicalName);
            }

            var type = entittypes[ent.LogicalName];

            TO_ENT_GENS[ent.LogicalName] = TO_ENTITY.MakeGenericMethod(type);

            return(TO_ENT_GENS[ent.LogicalName].Invoke(ent, new object[0]) as T);
        }
Exemplo n.º 5
0
        private WSDynamicEntity ReadSession(/*WSDataContext ZoneContext*/)
        {
            WSDynamicEntity entity = null;

            if (Meta != null && !string.IsNullOrEmpty(SessionID) && ZoneContext != null)
            {
                long init_ticks = DateTime.Now.Ticks;
                try
                {
                    status.AddNote("Zone:" + Meta.Zone, WSConstants.ACCESS_LEVEL.READ);

                    System.Reflection.MethodInfo mInfo = ZoneContext.GetType().GetMethod("GetTable", new Type[] { });

                    var tObj = mInfo.MakeGenericMethod(new Type[] { Meta.SessionType }).Invoke(ZoneContext, new object[] { });

                    Func <WSDynamicEntity, bool> func = s => s.readPropertyValue(WSConstants.PARAMS.SESSIONID.NAME, "").ToString().ToLower().Equals(SessionID.ToLower());

                    System.Reflection.MethodInfo[] methods = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);

                    var method = methods.FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(WSDynamicEntity));

                    entity = (WSDynamicEntity)method.Invoke(null, new object[] { tObj, func });
                }
                catch (Exception e) { CFunc.RegError(GetType(), e, ref status); }

                //if (ZoneContext != null) ZoneContext.Close(/*SessionID*/);

                TimeSpan ticks1 = new TimeSpan(DateTime.Now.Ticks - init_ticks); init_ticks = DateTime.Now.Ticks;
            }
            return(entity);
        }
        private TResult MapAsyncEnumerable <TResult>(Type elementType, IAsyncEnumerable <TSource?> source, CancellationToken cancellation)
        {
            var method = _mapAsyncEnumerableMethodInfo.MakeGenericMethod(elementType);
            var result = method.Invoke(null, new object[] { source, _resultMapper, cancellation });

            return((TResult)result !);
        }
Exemplo n.º 7
0
        protected override void EndProcessing()
        {
            base.EndProcessing();

            if (Width <= 0)
            {
                PSHost host = GetVariableValue("Host") as PSHost;
                Width = host.UI.RawUI.WindowSize.Width;
            }
            Height     = System.Math.Max(1, Height);
            Width      = System.Math.Max(1, Width);
            ColorSpace = ColorSpace.Substring(0, 1).ToUpperInvariant() + ColorSpace.Substring(1).ToLowerInvariant();
            var colorType = GetType().Assembly.GetType($"PoshCode.Pansies.ColorSpaces.{ColorSpace}");
            var colors    = (RgbColor[][])Get2DGradient.MakeGenericMethod(typeof(RgbColor), colorType).Invoke(null,
                                                                                                              new object[] { StartColor, EndColor, Height, Width, Reverse.ToBool() });

            if (Flatten || Height == 1)
            {
                foreach (var row in colors)
                {
                    foreach (var col in row)
                    {
                        WriteObject(col);
                    }
                }
            }
            else
            {
                WriteObject(colors, false);
            }
        }
Exemplo n.º 8
0
        public IMethod GetMethodT(string funcname, MethodParamList ttypes, MethodParamList types)
        {
            //这个实现还不完全
            //有个别重构下,判定比这个要复杂
            System.Reflection.MethodInfo _method = null;
            var ms = TypeForSystem.GetMethods();

            foreach (var m in ms)
            {
                if (m.Name == funcname && m.IsGenericMethodDefinition)
                {
                    var ts = m.GetGenericArguments();
                    var ps = m.GetParameters();
                    if (ts.Length == ttypes.Count && ps.Length == types.Count)
                    {
                        _method = m;
                        break;
                    }
                }
            }

            // _method = TypeForSystem.GetMethod(funcname, types.ToArraySystem());

            return(new Method_Common_System(this, _method.MakeGenericMethod(ttypes.ToArraySystem())));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Thread which listens for incoming NetMQMessages from the server and queues them up for handling
        /// </summary>
        private void Listener()
        {
            while (!isDone)
            {
                NetMQMessage message = null;

                if (clientSocket.TryReceiveMultipartMessage(TimeSpan.FromSeconds(1.0), ref message))
                {
                    string typeStr    = message[1].ConvertToString();
                    Type   objectType = Type.GetType(typeStr);

                    System.Reflection.MethodInfo method  = typeof(BsonMagic).GetMethod("DeserializeObject");
                    System.Reflection.MethodInfo generic = method.MakeGenericMethod(objectType);

                    Object[] methodParams = new Object[1] {
                        message[2].ToByteArray()
                    };

                    Object receivedObject = generic.Invoke(null, methodParams);

                    if (DataReceived != null)
                    {
                        DataReceived(receivedObject);
                    }
                    else
                    {
                        throw new ArgumentException("Data was received, but no event handler set!");
                    }
                }
            }
        }
        private async Task RemoveProcessedEvent(CqrsEventProcessedEvent request, System.Reflection.MethodInfo getRepositoryMethod, CancellationToken cancellationToken)
        {
            _logger.Debug($"Getting destination entity repository. DestinationTypeName: {request.DestinationTypeName}");
            var     destinationEntityType             = Type.GetType(request.DestinationTypeName);
            var     genericMethodForDestinationEntity = getRepositoryMethod.MakeGenericMethod(destinationEntityType);
            dynamic destinationEntityRepository       = genericMethodForDestinationEntity.Invoke(_cqrsRepositoryFactory, null);

            _logger.Debug($"Built {nameof(CqrsRepositoryFactory)}");
            using var uow = _unitOfWorkManager.Get();
            _logger.Debug($"Fetched destination entity by Id. Id: {request.DestinationId}");
            var cqrsEntity = await destinationEntityRepository.GetByIdAsync(request.DestinationId, cancellationToken);

            var baseCqrsEntity = cqrsEntity as BaseCqrsEntity;

            _logger.Debug($"Fetched BaseCqrsEntity. Id: {request.DestinationId}");
            var @event = baseCqrsEntity?.ProcessedEvents.FirstOrDefault(f => f.Id == request.Id);

            if (@event != null)
            {
                _logger.Debug($"Removing event. Id: {@event.Id}");
                baseCqrsEntity.RemoveProcessedEvent(@event);
                await destinationEntityRepository.UpdateAsync(cqrsEntity, cancellationToken);

                _logger.Debug($"Removed event");
            }
            uow.Commit();
        }
        internal static MessagePackSerializer CreateInternal(SerializationContext context, Type targetType, PolymorphismSchema schema)
        {
#if UNITY
            return
                ((
                     Delegate.CreateDelegate(
                         typeof(Func <SerializationContext, PolymorphismSchema, object>),
                         CreateInternal_2.MakeGenericMethod(targetType)
                         )
                     as Func <SerializationContext, PolymorphismSchema, object>)(context, schema) as MessagePackSerializer);
#else
            return
                ((CreateInternal_2.MakeGenericMethod(targetType).CreateDelegate(typeof(Func <SerializationContext, PolymorphismSchema, object>))
                  as Func <SerializationContext, PolymorphismSchema, object>)(context, schema) as MessagePackSerializer);
#endif // UNITY
        }
Exemplo n.º 12
0
        /// <summary>
        /// Get MethodInfo to Invoke through Reflection
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="methodName"></param>
        /// <param name="columnType"></param>
        /// <returns></returns>
        protected static System.Reflection.MethodInfo GetMethodInfo(System.Type entityType, System.String methodName, System.Type columnType)
        {
            System.Reflection.MethodInfo[] methods = entityType.GetMethods();
            System.Reflection.MethodInfo   method  = methods.Where(m => m.Name == methodName && m.IsGenericMethod).FirstOrDefault();

            return(method.MakeGenericMethod(new System.Type[] { columnType }));
        }
        public void DeserializeCollection(string serializedItems)
        {
            string[] items = serializedItems.Split('|');
            for (int i = 0; i < items.Length; i++)
            {
                string[] keyItem = items[i].Split('=');
                if (keyItem.Length < 1)
                {
                    throw new SerializationException("Unexpected serialization data format.");
                }

                string colKey   = keyItem[0];
                string itemData = System.Text.Encoding.UTF8.GetString(Hex.GetBytes(keyItem[1]));

                Type tType = typeof(T);
                System.Reflection.MethodInfo getFromSerializedMethod = tType.GetMethod("FromSerializedData"
                                                                                       , System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy
                                                                                       , null
                                                                                       , new Type[] { typeof(System.String) }
                                                                                       , null);
                if (getFromSerializedMethod == null)
                {
                    throw new Exception("Unable to determine method to get new item from serialized data.");
                }

                // This takes the method we found a few lines up, and constructs a generic call with the "T"
                //   data type attached.  This is the MethodInfo we'll actually invoke to call the method.
                System.Reflection.MethodInfo genericMethodCall = getFromSerializedMethod.MakeGenericMethod(tType);

                // This should call this same method for the Type of the specified property.
                T qa = (T)genericMethodCall.Invoke(null, new object[] { itemData });

                this.Add(qa, colKey);
            }
        }
        private ValueTask <TResult> MapSingleElementStream <TResult>(IAsyncEnumerable <TSource?> source, CancellationToken cancellation)
        {
            var method = _mapSingleElementStreamMethodInfo.MakeGenericMethod(typeof(TResult));
            var result = method.Invoke(null, new object[] { source, _resultMapper, cancellation });

            return((ValueTask <TResult>)result !);
        }
        internal static IMessagePackSingleObjectSerializer CreateReflectionInternal(SerializationContext context, Type targetType)
        {
#if UNITY_ANDROID || UNITY
            return
                ((
                     Delegate.CreateDelegate(
                         typeof(Func <SerializationContext, object>),
                         CreateReflectionInternal_1.MakeGenericMethod(targetType)
                         )
                     as Func <SerializationContext, object>)(context) as IMessagePackSingleObjectSerializer);
#else
            return
                ((CreateReflectionInternal_1.MakeGenericMethod(targetType).CreateDelegate(typeof(Func <SerializationContext, object>))
                  as Func <SerializationContext, object>)(context) as IMessagePackSingleObjectSerializer);
#endif
        }
Exemplo n.º 16
0
        public sealed override void ReceivedSettings(ReceivedSettingsPayload payload)
        {
            var genAutoPopInfo = AutoPopInfo.MakeGenericMethod(settings.GetType());

            genAutoPopInfo.Invoke(null, new object[] { settings, payload.Settings });
            ApplySettings();
            Connection.SetSettingsAsync(JObject.FromObject(settings));
        }
        /// <summary>
        /// Cria a expressão de acesso ao membro.
        /// </summary>
        /// <returns></returns>
        public override System.Linq.Expressions.Expression CreateMemberAccessExpression()
        {
            var expression = System.Linq.Expressions.Expression.Constant(base.MemberName);

            return(System.Linq.Expressions.Expression.Call(DataRowFieldMethod.MakeGenericMethod(new Type[] {
                this.columnDataType
            }), base.ParameterExpression, expression));
        }
Exemplo n.º 18
0
 public static string GetDisplayName(System.Reflection.MethodInfo method, object[] arglist)
 {
     if (method.IsGenericMethod)
     {
         method = method.MakeGenericMethod(GetArgumentTypes(arglist));
     }
     return(GetDisplayName(method, method.Name, arglist));
 }
        /// <summary>
        /// Cria a expressão de acesso ao membro.
        /// </summary>
        /// <returns></returns>
        public override System.Linq.Expressions.Expression CreateMemberAccessExpression()
        {
            var expression = System.Linq.Expressions.Expression.Constant(base.MemberName);

            return(System.Linq.Expressions.Expression.Call(PropertyMethod.MakeGenericMethod(new Type[] {
                this._propertyType
            }), base.ParameterExpression, expression));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the generic method for a given type (caches internally for speedup).
        /// </summary>
        /// <param name="classContainingMethod">The class containing the method.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="genericType">Type to find a generic method for.</param>
        /// <param name="paramTypes">The parameter types to resolve possible ambiguity (if necessary, may be null).</param>
        /// <returns></returns>
        public static System.Reflection.MethodInfo GetGenericMethod(Type classContainingMethod, string methodName, Type genericType, Type[] paramTypes)
        {
            // NOTE: See also this discussion about an maybe easier way:
            // How do I use reflection to call a generic method?
            // http://stackoverflow.com/a/232621


            if (string.IsNullOrWhiteSpace(methodName) || null == genericType)
            {
                return(null);
            }

            string key = classContainingMethod.ToString() + "#" + methodName + "#" + genericType.ToString();

            if (null != paramTypes)
            {
                foreach (Type t in paramTypes)
                {
                    key += "#" + t.ToString();
                }
            }
            if (_GenericMethodsCache.ContainsKey(key))
            {
                // Cache hit
                return(_GenericMethodsCache[key]);
            }

            // Using System.Type to call a generic method
            // http://stackoverflow.com/a/14222568
            //System.Reflection.MethodInfo method = this.GetType().GetMethods()
            //    .First(m => m.Name == "QuerySingle" && m.GetParameters().Any(par => par.ParameterType == typeof(IDictionary<string, object>)));
            System.Reflection.MethodInfo method = null;
            if (null != paramTypes)
            {
                method = classContainingMethod.GetMethod(methodName, paramTypes);
            }
            else
            {
                method = classContainingMethod.GetMethod(methodName);
            }

            if (null == method)
            {
                return(null);
            }

            System.Reflection.MethodInfo genericMethod = method.MakeGenericMethod(genericType);
            if (null == genericMethod)
            {
                return(null);
            }

            // Cache found generic method
            _GenericMethodsCache[key] = genericMethod;
            return(genericMethod);
        }
Exemplo n.º 21
0
 /// <summary>
 /// Generate default variables to an option
 /// </summary>
 /// <param name="options"></param>
 public static void GenerateDefaultVariables(ITypeOptions options)
 {
     foreach (KeyValuePair <Type, string> variableType in ReflectionHelper.VariableTypes)
     {
         System.Reflection.MethodInfo method = typeof(BaseTypeGoInfo).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)
                                               .FirstOrDefault(x => x.Name == "Generate" && x.GetGenericArguments().Length == 1);
         System.Reflection.MethodInfo genericMethod = method.MakeGenericMethod(variableType.Key);
         genericMethod.Invoke(null, new object[] { options });
     }
 }
        private static IOrderedQueryable<T> Sort<T>(this IQueryable<T> queryable, SystemLinq.LambdaExpression lambdaExpression, MethodInfo methodInfo)
        {
            queryable.AssertNotNull(nameof(queryable));
            var exp = lambdaExpression.CheckNotNull(nameof(lambdaExpression)).Body;
            var resultType = exp.Type;
            var funcType = typeof(Func<,>).MakeGenericType(typeof(T), resultType);
            var lambdaExpressionMethodInfo = MethodInfos.Expression.Lambda.MakeGenericMethod(funcType);

            var funcExpression = lambdaExpressionMethodInfo.Invoke(null, new object[] { exp, lambdaExpression.Parameters.ToArray() });

            var method = methodInfo.MakeGenericMethod(typeof(T), resultType);
            var result = method.Invoke(null, new object[] { queryable, funcExpression! });
Exemplo n.º 23
0
        public static EntitySetConfiguration AddClrObject(this ODataModelBuilder builder, AssemblyTableInfo assemblyTableInfo)
        {
            System.Reflection.MethodInfo methodEntitySet = builder.GetType().GetMethod("EntitySet");

            var genericEntityType = methodEntitySet.MakeGenericMethod(assemblyTableInfo.ClrTypeClass);
            //Registers an EntitySet<genericEntityType>(EntitySetName);
            var entitySetConfiguration = genericEntityType.Invoke(builder, new object[] { assemblyTableInfo.EntitySetName });

            listTablesInfo.Add(assemblyTableInfo);

            return(entitySetConfiguration as EntitySetConfiguration);
        }
Exemplo n.º 24
0
            public T CreateUsingNested <T>(string name) where T : VisualElement, new()
            {
                var t          = typeof(T);
                var nestedType = NestedTypes.Where(x => x.Name == name && (x.IsSubclassOf(t) || x.IsSubclassOf(t.BaseType))).FirstOrDefault();

                if (nestedType != null)
                {
                    return(CreateMethod_INFO.MakeGenericMethod(nestedType).Invoke(m_Base, new object[1] {
                        name
                    }) as T);
                }
                return(m_Base.CreateElement <T>());
            }
Exemplo n.º 25
0
        public AgentEventRectifier(IEnumerable <Type> types, INotifierQueryable agent_instance)
        {
            this._Types     = types.ToArray();
            _RemoveHandlers = new List <System.Action>();


            Type agentType = typeof(INotifierQueryable);

            System.Reflection.MethodInfo agentQueryNotifier = agentType.GetMethod(nameof(INotifierQueryable.QueryNotifier));

            foreach (Type type in _Types)
            {
                if (!type.IsInterface)
                {
                    continue;
                }
                System.Reflection.MethodInfo agentQueryNotifierT = agentQueryNotifier.MakeGenericMethod(type);


                object notifyInstance = agentQueryNotifierT.Invoke(agent_instance, new object[0]);

                Type notifyTypeT = typeof(INotifier <>).MakeGenericType(type);


                System.Reflection.EventInfo notifySupply   = notifyTypeT.GetEvent(nameof(INotifier <object> .Supply));
                System.Reflection.EventInfo notifyUnsupply = notifyTypeT.GetEvent(nameof(INotifier <object> .Unsupply));

                Utility.Reflection.TypeMethodCatcher catcherSupply       = new Regulus.Utility.Reflection.TypeMethodCatcher((System.Linq.Expressions.Expression <Action <AgentEventRectifier> >)(ins => ins._Supply <object>(null)));
                System.Reflection.MethodInfo         supplyGenericMethod = catcherSupply.Method.GetGenericMethodDefinition();
                System.Reflection.MethodInfo         supplyMethod        = supplyGenericMethod.MakeGenericMethod(type);

                Utility.Reflection.TypeMethodCatcher catcherUnsupply       = new Regulus.Utility.Reflection.TypeMethodCatcher((System.Linq.Expressions.Expression <Action <AgentEventRectifier> >)(ins => ins._Unsupply <object>(null)));
                System.Reflection.MethodInfo         unsupplyGenericMethod = catcherUnsupply.Method.GetGenericMethodDefinition();
                System.Reflection.MethodInfo         unsupplyMethod        = unsupplyGenericMethod.MakeGenericMethod(type);

                Type actionT1 = typeof(System.Action <>);
                Type actionT  = actionT1.MakeGenericType(type);



                Delegate delegateSupply   = Delegate.CreateDelegate(actionT, this, supplyMethod);
                Delegate delegateUnsupply = Delegate.CreateDelegate(actionT, this, unsupplyMethod);
                notifySupply.AddEventHandler(notifyInstance, delegateSupply);
                notifyUnsupply.AddEventHandler(notifyInstance, delegateUnsupply);
                _RemoveHandlers.Add(() =>
                {
                    notifySupply.RemoveEventHandler(notifyInstance, delegateSupply);
                    notifyUnsupply.RemoveEventHandler(notifyInstance, delegateUnsupply);
                });
            }
        }
Exemplo n.º 26
0
        internal static object GetDefaultValue(Type type)
        {
            // null is always the default for non value types and Nullable<>
            if (!type.IsValueType ||
                (type.IsGenericType &&
                 typeof(Nullable <>) == type.GetGenericTypeDefinition()))
            {
                return(null);
            }
            System.Reflection.MethodInfo getDefaultMethod = s_getDefaultMethod.MakeGenericMethod(type);
            object defaultValue = getDefaultMethod.Invoke(null, new object[] { });

            return(defaultValue);
        }
Exemplo n.º 27
0
        private static IOrderedQueryable <T> Sort <T>(this IQueryable <T> queryable, LambdaExpression lambdaExpression, MethodInfo methodInfo)
        {
            var exp        = lambdaExpression.Body;
            var resultType = exp.Type;
            var funcType   = typeof(Func <,>).MakeGenericType(typeof(T), resultType);
            var lambdaExpressionMethodInfo = MethodInfos.Expression.Lambda.MakeGenericMethod(funcType);

            var funcExpression = lambdaExpressionMethodInfo.Invoke(null, new object[] { exp, lambdaExpression.Parameters.ToArray() });

            var method = methodInfo.MakeGenericMethod(typeof(T), resultType);
            var result = method.Invoke(null, new object[] { queryable, funcExpression });

            return((IOrderedQueryable <T>)result);
        }
            private static void AddPrefab(string name, System.Type type)
            {
                if (PrefabAlreadyExists(name))
                {
                    Fabric.Internal.Editor.Utils.Log("{0} already exists in this scene", name);
                    return;
                }

                GameObject gameObject = new GameObject(name);

                System.Reflection.MethodInfo addComponent        = typeof(GameObject).GetMethod("AddComponent", new System.Type[] {});
                System.Reflection.MethodInfo addComponentGeneric = addComponent.MakeGenericMethod(type);
                addComponentGeneric.Invoke(gameObject, null);
            }
Exemplo n.º 29
0
 public static T2 ToSigned <T2>(T input)
 {
     if (IsSigned)
     {
         return((T2)(object)input);
     }
     // T is Unsigned
     // t is signed type for T
     System.Type t = MapUnsignedSigned[typeof(T)];
     // TSigned UnsignedToSigned<TUnsigned, TSigned>(TUnsigned ulongValue)
     // return UnsignedToSigned<T, t> (input);
     System.Reflection.MethodInfo method        = typeof(Number <T>).GetMethod("UnsignedToSigned");
     System.Reflection.MethodInfo genericMethod = method.MakeGenericMethod(typeof(T), t);
     return((T2)genericMethod.Invoke(null, new object[] { input }));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Gets the generic method for a given type (caches internally for speedup).
        /// <locDE><para />Holt die generische Methode für den angegebenen Typ (cacht intern zur Geschwindigkeitssteigerung).</locDE>
        /// </summary>
        /// <param name="classContainingMethod">The class containing the method.<locDE><para />Die Klasse, welche die Methode enthält.</locDE></param>
        /// <param name="methodName">The name of the method.<locDE><para />Der Methodenname.</locDE></param>
        /// <param name="genericType">The type to find a generic method for.<locDE><para />Der Typ, für welchen eine generische Methode gefunden werden soll.</locDE></param>
        /// <param name="bindingFlags">The binding flags.<locDE><para />Die Bindungsflags.</locDE></param>
        /// <returns>MethodInfo object (if found).<locDE><para />MethodInfo-Objekt (falls gefunden).</locDE></returns>
        public static System.Reflection.MethodInfo GetGenericMethod(Type classContainingMethod, string methodName,
                                                                    System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public,
                                                                    Type genericType = null)
        {
            // NOTE: See also this discussion about an maybe easier way:
            // How do I use reflection to call a generic method?
            // http://stackoverflow.com/a/232621


            if (string.IsNullOrWhiteSpace(methodName))
            {
                return(null);
            }

            string key = classContainingMethod.ToStringInvariant() + "#" + methodName + "#" + genericType.ToStringInvariant() + "#" + bindingFlags.ToStringInvariant();

            if (_GenericMethodsCache.ContainsKey(key))
            {
                // Cache hit
                return(_GenericMethodsCache[key]);
            }

            // Using System.Type to call a generic method
            // http://stackoverflow.com/a/14222568
            //System.Reflection.MethodInfo method = this.GetType().GetMethods()
            //    .First(m => m.Name == "QuerySingle" && m.GetParameters().Any(par => par.ParameterType == typeof(IDictionary<string, object>)));
            System.Reflection.MethodInfo method = null;
            method = classContainingMethod.GetMethod(methodName, bindingFlags);

            if (null == method)
            {
                return(null);
            }

            if (null != genericType)
            {
                System.Reflection.MethodInfo genericMethod = method.MakeGenericMethod(genericType);
                if (null == genericMethod)
                {
                    return(null);
                }
                method = genericMethod;
            }

            // Cache found generic method
            _GenericMethodsCache[key] = method;
            return(method);
        }