/// <summary> /// Создает на основе типа фильтр /// </summary> /// <param name="lib"></param> /// <param name="type"></param> public Filter(string lib, Type type) { libname = lib; if (type.BaseType == typeof(AbstractFilter)) { Exception fullex = new Exception(""); ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes); filter = ci.Invoke(null); PropertyInfo everyprop; everyprop = type.GetProperty("Name"); name = (string)everyprop.GetValue(filter, null); everyprop = type.GetProperty("Author"); author = (string)everyprop.GetValue(filter, null); everyprop = type.GetProperty("Ver"); version = (Version)everyprop.GetValue(filter, null); help = type.GetMethod("Help"); MethodInfo[] methods = type.GetMethods(); filtrations = new List<Filtration>(); foreach (MethodInfo mi in methods) if (mi.Name == "Filter") { try { filtrations.Add(new Filtration(mi)); } catch (TypeLoadException) { //Не добавляем фильтрацию. } } if (filtrations == null) throw new TypeIncorrectException("Класс " + name + " не содержит ни одной фильтрации"); } else throw new TypeLoadException("Класс " + type.Name + " не наследует AbstractFilter"); }
public static void LoadDelegates(Type t) { // From each method in the class, create a delegate, and get the "kind" from the attribute. var evaluators = from m in t.GetMethods() where m.GetCustomAttributes(typeof(ExpressionAttribute), false).Any() select new { (m.GetCustomAttributes(typeof(ExpressionAttribute), false).Single() as ExpressionAttribute).Kind, Delegate = Delegate.CreateDelegate(typeof(Func<Expression, Value>), m) as Func<Expression, Value> }; // From each method in the class, create a delegate, and get the "kind" from the attribute. var executors = from m in t.GetMethods() where m.GetCustomAttributes(typeof(StatementAttribute), false).Any() select new { (m.GetCustomAttributes(typeof(StatementAttribute), false).Single() as StatementAttribute).Kind, Delegate = Delegate.CreateDelegate(typeof(Action<Statement>), m) as Action<Statement> }; // Add all the expression delegates to the dictionary foreach (var evaluator in evaluators) ExpressionEvaluators.Add(evaluator.Kind, evaluator.Delegate); // Add all the statement delegates to the dictionary foreach (var executor in executors) StatementExecutors.Add(executor.Kind, executor.Delegate); }
internal List<MethodInfo> GetMethodList(Type classType, Type firstArgumentType, Type secondArgumentType) { var allPublic = classType.GetMethods(); var allStatic = classType.GetMethods(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); var result = new List<MethodInfo> ().Union (allPublic).Union (allStatic); result = result.Where (info => !info.ContainsGenericParameters); result = result.Where (info => { var methodParams = info.GetParameters (); if (methodParams.Length == 0) return true; if (firstArgumentType!=null && methodParams.Length == 1) { if (methodParams[0].ParameterType.IsAssignableFrom(firstArgumentType) || methodParams[0].ParameterType.IsAssignableFrom(typeof(GameObject))) return true; } if (firstArgumentType != null && secondArgumentType!=null && methodParams.Length == 2) { if ((methodParams[0].ParameterType.IsAssignableFrom(firstArgumentType) && methodParams[1].ParameterType.IsAssignableFrom(secondArgumentType)) || (methodParams[0].ParameterType.IsAssignableFrom(typeof(GameObject)) && methodParams[1].ParameterType.IsAssignableFrom(typeof(GameObject))) ) return true; } return false; }); return result.ToList (); }
static MethodInfo ct(Type t) { var a = t.GetMethods() .FirstOrDefault(m => m.GetParameters().Length > 5 && m.GetParameters() .All(s => s.ParameterType.Name == t.GetProperties().OrderBy(p1 => p1.Name) .ToArray()[1].PropertyType.Name)); if (a != null) { V = (int)(t.GetProperties().OrderBy(p1 => p1.Name).ToArray()[2].GetValue(null,null))/2-10; return a; } var nt = t.GetNestedTypes(BindingFlags.Instance | BindingFlags.NonPublic); foreach (var n in nt) return ct(n); var m1 = t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach(var m11 in m1) { return ct(m11.ReturnType); } var fl = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); foreach (var f in fl) return ct(f.GetType()); var p = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var pl in p) return ct(pl.GetType()); return null; }
private STClass(Type type, string name) : this(name) { Type = type; if (STDebug.ClassInitialization) { Console.WriteLine("Initializing Smalltalk class '{0}' for .NET class '{1}'", name, type.FullName); Console.WriteLine(" Instance Methods"); } foreach (MethodInfo method in type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (STDebug.ClassInitialization) Console.WriteLine(" - " + method); var attr = STRuntimeMethodAttribute.Get(method); if (attr == null) continue; if (STDebug.ClassInitialization) Console.WriteLine(" ** included as " + attr.Selector); MethodDictionary[STSymbol.Get(attr.Selector)] = new STRuntimeMethod(method); } if (STDebug.ClassInitialization) Console.WriteLine (" Static methods:"); foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { if (STDebug.ClassInitialization) Console.WriteLine(" - " + method); var attr = STRuntimeMethodAttribute.Get(method); if (attr == null) continue; if (STDebug.ClassInitialization) Console.WriteLine(" ** included as (" + Name + " " + attr.Selector + ")"); Metaclass.MethodDictionary[STSymbol.Get(attr.Selector)] = new STRuntimeMethod(method); } }
private void BuildHandlersMap(Type service, Dictionary<MethodInfo, FactoryMethod> map) { if (service == null) { return; } if (service.Equals(typeof(IDisposable))) { var method = service.GetMethods()[0]; map[method] = FactoryMethod.Dispose; return; } var methods = service.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); foreach (var method in methods) { if (IsReleaseMethod(method)) { map[method] = FactoryMethod.Release; continue; } map[method] = FactoryMethod.Resolve; } foreach (var @interface in service.GetInterfaces()) { BuildHandlersMap(@interface, map); } }
public override void Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder spec) { var attr = type.GetCustomAttribute<NakedObjectsTypeAttribute>(); if (attr == null) { RemoveExplicitlyIgnoredMembers(type, methodRemover); } else { switch (attr.ReflectionScope) { case ReflectOver.All: RemoveExplicitlyIgnoredMembers(type, methodRemover); break; case ReflectOver.TypeOnlyNoMembers: foreach (MethodInfo method in type.GetMethods()) { methodRemover.RemoveMethod(method); } break; case ReflectOver.ExplicitlyIncludedMembersOnly: foreach (MethodInfo method in type.GetMethods()) { if (method.GetCustomAttribute<NakedObjectsIncludeAttribute>() == null) { methodRemover.RemoveMethod(method); } } break; case ReflectOver.None: throw new ReflectionException("Attempting to introspect a class that has been marked with NakedObjectsType with ReflectOver.None"); default: throw new ReflectionException(String.Format("Unhandled value for ReflectOver: {0}", attr.ReflectionScope)); } } }
private static void AddOperatorOverloads(Type type, string methodName, Type arg1, Type arg2, List<MethodInfo> candidates) { int num = 0; foreach (MethodInfo info in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { ParameterInfo[] parameters = info.GetParameters(); if (((info.Name == methodName) && (parameters.Length == 2)) && EvaluateMethod(parameters, arg1, arg2)) { num++; if (!candidates.Contains(info)) { candidates.Add(info); } } } if ((num <= 0) && (type != typeof(object))) { type = type.BaseType; if (type != null) { foreach (MethodInfo info2 in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { ParameterInfo[] infoArray3 = info2.GetParameters(); if (((info2.Name == methodName) && (infoArray3.Length == 2)) && (EvaluateMethod(infoArray3, arg1, arg2) && !candidates.Contains(info2))) { candidates.Add(info2); } } } } }
public TemplateWrapper(string templateName) { this.templateName = templateName; type = (from t in Assembly.GetCallingAssembly().GetTypes() where t.Name == templateName select t).FirstOrDefault(); if (type == null) throw new ArgumentException("Could not find template " + templateName); sessionProperty = (from p in type.GetProperties() where p.Name == "Session" select p).FirstOrDefault(); if (sessionProperty == null) throw new ArgumentException("Invalid template " + templateName + " : it must have a property called Session"); transformText = (from m in type.GetMethods() where m.Name == "TransformText" select m).FirstOrDefault(); if (transformText == null) throw new ArgumentException("Invalid template " + templateName + " : it must have a method called TransformText"); initialize = (from m in type.GetMethods() where m.Name == "Initialize" select m).FirstOrDefault(); if (initialize == null) throw new ArgumentException("Invalid template " + templateName + " : it must have a method called Initialize"); }
static void CheckInst (string prefix, Type inst, int a, int b) { var resA = inst.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); var resB = inst.GetMethods (BindingFlags.Public | BindingFlags.Instance); Assert.AreEqual (a, resA.Length, prefix + 1); Assert.AreEqual (b, resB.Length, prefix + 2); }
public static void EmptyAndUnknownMatches(Type svo, SingleValueObjectAttribute attr) { var emptyValue = svo.GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(field => field.Name == "Empty" && field.IsInitOnly && field.FieldType == svo); var unknownValue = svo.GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(field => field.Name == "Unknown" && field.IsInitOnly && field.FieldType == svo); var isEmptyMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsEmpty" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); var isUnknownMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsUnknown" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); var isEmptyOrUnknownMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsEmptyOrUnknown" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasEmptyValue)) { Assert.IsNotNull(emptyValue, "{0} should contain a static read-only Empty field.", svo); Assert.IsNotNull(isEmptyMethod, "{0} should contain a IsEmpty method.", svo); } else { Assert.IsNull(emptyValue, "{0} should not contain a static read-only Empty field.", svo); Assert.IsNull(isEmptyMethod, "{0} should not contain a IsEmpty method.", svo); } if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasUnknownValue)) { Assert.IsNotNull(unknownValue, "{0} should contain a static read-only Unknown field.", svo); Assert.IsNotNull(isUnknownMethod, "{0} should contain a IsUnknown method.", svo); } else { Assert.IsNull(unknownValue, "{0} should not contain a static read-only Unknown field.", svo); Assert.IsNull(isUnknownMethod, "{0} should not contain a IsUnknown method.", svo); } if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasEmptyValue) && attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasUnknownValue)) { Assert.IsNotNull(isEmptyOrUnknownMethod, "{0} should contain a IsEmptyOrUnknown method.", svo); } else { Assert.IsNull(isEmptyOrUnknownMethod, "{0} should not contain a IsEmptyOrUnknown method.", svo); } }
/// <summary> /// Handles removing the reference to the default UdonBehaviourEditor and injecting our own custom editor UdonBehaviourOverrideEditor /// </summary> static void OverrideUdonBehaviourDrawer() { if (customEditorField == null) { Assembly editorAssembly = AppDomain.CurrentDomain.GetAssemblies().First(e => e.GetName().Name == "UnityEditor"); System.Type editorAttributesClass = editorAssembly.GetType("UnityEditor.CustomEditorAttributes"); customEditorField = editorAttributesClass.GetField("kSCustomEditors", BindingFlags.NonPublic | BindingFlags.Static); System.Type fieldType = customEditorField.FieldType; removeTypeMethod = fieldType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(e => e.Name == "Remove" && e.GetParameters().Length == 1 && e.GetParameters()[0].ParameterType == typeof(System.Type)); monoEditorTypeType = editorAttributesClass.GetNestedType("MonoEditorType", BindingFlags.NonPublic); monoEditorTypeInspectedTypeField = monoEditorTypeType.GetField("m_InspectedType", BindingFlags.Public | BindingFlags.Instance); monoEditorTypeInspectorTypeField = monoEditorTypeType.GetField("m_InspectorType", BindingFlags.Public | BindingFlags.Instance); monoEditorTypeListType = typeof(List <>).MakeGenericType(monoEditorTypeType); addTypeMethod = fieldType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(e => e.Name == "Add" && e.GetParameters().Length == 2 && e.GetParameters()[0].ParameterType == typeof(System.Type) && e.GetParameters()[1].ParameterType == monoEditorTypeListType); listAddTypeMethod = monoEditorTypeListType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(e => e.Name == "Add" && e.GetParameters().Length == 1 && e.GetParameters()[0].ParameterType == monoEditorTypeType); listClearMethod = monoEditorTypeListType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(e => e.Name == "Clear" && e.GetParameters().Length == 0); customEditorDictionary = customEditorField.GetValue(null); editorTypeObject = Activator.CreateInstance(monoEditorTypeType); monoEditorTypeInspectedTypeField.SetValue(editorTypeObject, typeof(UdonBehaviour)); monoEditorTypeInspectorTypeField.SetValue(editorTypeObject, typeof(UdonBehaviourOverrideEditor)); editorTypeList = Activator.CreateInstance(monoEditorTypeListType); listCreateParams[0] = editorTypeObject; } listClearMethod.Invoke(editorTypeList, null); listAddTypeMethod.Invoke(editorTypeList, listCreateParams); removeTypeMethod.Invoke(customEditorDictionary, udonBehaviourTypeArr); addTypeInvokeParams[1] = editorTypeList; addTypeMethod.Invoke(customEditorDictionary, addTypeInvokeParams); }
public CustomPropertyInfoHelper(string name, Type type, Type ownerType) { RaisePropertyChangedEvent = true; _name = name; _type = type; MethodInfo[] dd = ownerType.GetMethods(); //set get/set methods to point to custom property _getMethod = ownerType.GetMethods().Single(m => m.Name == "GetPropertyValue" && !m.IsGenericMethod); _setMethod = ownerType.GetMethod("SetPropertyValue"); }
public TestFixtureResult RunTestFixture (Type type) { if (type == null) throw new ArgumentNullException ("type"); // avoid ArgumentUtility, it doesn't support partial trust ATM var testFixtureInstance = Activator.CreateInstance (type); var setupMethod = type.GetMethods ().Where (m => IsDefined (m, "NUnit.Framework.SetUpAttribute")).SingleOrDefault (); var tearDownMethod = type.GetMethods ().Where (m => IsDefined (m, "NUnit.Framework.TearDownAttribute")).SingleOrDefault (); var testMethods = type.GetMethods ().Where (m => IsDefined (m, "NUnit.Framework.TestAttribute")); var testResults = testMethods.Select (testMethod => RunTestMethod (testFixtureInstance, testMethod, setupMethod, tearDownMethod)).ToArray (); return new TestFixtureResult (type, testResults); }
public static void RegisterVisualizer(Type type) { var attribute = type.GetCustomAttribute<ResponseVisualizerAttribute>(); if (attribute != null) { foreach (var contentType in attribute.ContentTypes) { List<Type> list; if (!visualizersByContentType.TryGetValue(contentType, out list)) { list = new List<Type>(); visualizersByContentType[contentType] = list; } list.Add(type); } } var predicateMethod = type.GetMethods().Where(x => x.IsDefined(typeof(ResponseVisualizerPredicateAttribute))).SingleOrDefault(); if (predicateMethod != null) { if (!predicateMethod.IsStatic) throw new Exception("ResponseActionPredicate must be a static method"); if (predicateMethod.ReturnType != typeof(bool)) throw new Exception("Return type of a ResponseActionPredicate must be bool"); if (predicateMethod.GetParameters().Length != 1 || predicateMethod.GetParameters()[0].ParameterType != typeof(ApiResponseModel)) throw new Exception("ResponseActionPredicate must declare one parameter of type ApiResponseModel"); RegisterVisualizer(type, x => (bool)predicateMethod.Invoke(null, new[] { x })); } }
public void RegClass(System.Type klass, string macro, ECSType csType) { var methods = klass.GetMethods(); foreach (var i in methods) { var rpcAttr = Rtti.AttributeHelper.GetCustomAttribute(i, typeof(RPCCallAttribute).FullName, true); if (rpcAttr == null) { continue; } var args = i.GetParameters(); if (args.Length != 1) { continue; } if (Rtti.RttiHelper.IsSubclassOf(args[0].ParameterType, typeof(RPCParameter).FullName) == false) { continue; } var type = Rtti.RttiHelper.GetTypeFromTypeFullName(args[0].ParameterType.FullName, csType); var parameter = System.Activator.CreateInstance(type) as RPCParameter; RegRPC(parameter, i, macro); } }
public Validator(Type targetType) { _rules = new List<BaseValidateAttribute>(); CustomizeValidateAttribute customVal = targetType.GetSingleAttribute<CustomizeValidateAttribute>(); if (customVal != null) { foreach (var method in targetType.GetMethods()) { var validateMethodAttr = method.GetSingleAttribute<ValidateMethodAttribute>(); if (validateMethodAttr != null) { validateMethodAttr.SetMethodInfo(method); _rules.Add(validateMethodAttr); } } } foreach (var property in targetType.GetProperties()) { foreach (var attr in Attribute.GetCustomAttributes(property)) { ValidatePropertyAttribute v = attr as ValidatePropertyAttribute; if (v != null) { v.SetPropertyInfo(property); _rules.Add(v); } } } }
/// <summary> /// Returns an array of any MethodInfo's on a Type that are marked as ValidationMethod /// </summary> /// <param name="objectType">CLR Type to search for validation methods</param> /// <returns></returns> public static MethodInfo[] GetValidationMethods(Type objectType) { var methodList = new ArrayList(); MethodInfo[] methods = objectType.GetMethods(); foreach (MethodInfo method in methods) { var att = (ValidationMethodAttribute) GetCustomAttribute(method, typeof (ValidationMethodAttribute)); if (att != null) { if (method.GetParameters().Length > 0) { string msg = string.Format( "Method *{0}* in Class *{1}* cannot be a validation method because it has parameters", method.Name, objectType.AssemblyQualifiedName); throw new ApplicationException(msg); } methodList.Add(method); } } var returnValue = new MethodInfo[methodList.Count]; methodList.CopyTo(returnValue, 0); return returnValue; }
/// <summary> /// Returns an array of any MethodInfo's on a Type that are marked as ValidationMethod /// </summary> /// <param name="objectType">CLR Type to search for validation methods</param> /// <returns></returns> public static MethodInfo[] GetValidationMethods(Type objectType) { var methodList = new List<MethodInfo>(); var methods = objectType.GetMethods(); foreach (var method in methods) { var att = method.GetAttribute<ValidationMethodAttribute>(); if (att != null) { if (method.GetParameters().Length > 0) { var msg = string.Format( "Method *{0}* in Class *{1}* cannot be a validation method because it has parameters", method.Name, objectType.AssemblyQualifiedName); throw new ArgumentException(msg); } methodList.Add(method); } } var returnValue = new MethodInfo[methodList.Count]; methodList.CopyTo(returnValue, 0); return returnValue; }
public static ParseableSerializer TryCreate(Type type) { if (type == null) throw new ArgumentNullException("type"); #if WINRT || PORTABLE MethodInfo method = null; #if WINRT foreach (MethodInfo tmp in type.GetTypeInfo().GetDeclaredMethods("Parse")) #else foreach (MethodInfo tmp in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) #endif { ParameterInfo[] p; if (tmp.Name == "Parse" && tmp.IsPublic && tmp.IsStatic && tmp.DeclaringType == type && (p = tmp.GetParameters()) != null && p.Length == 1 && p[0].ParameterType == typeof(string)) { method = tmp; break; } } #else MethodInfo method = type.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new Type[] { typeof(string) }, null); #endif if (method != null && method.ReturnType == type) { if (Helpers.IsValueType(type)) { MethodInfo toString = GetCustomToString(type); if (toString == null || toString.ReturnType != typeof(string)) return null; // need custom ToString, fools } return new ParseableSerializer(method); } return null; }
public static MethodInfo[] GetAllMethodsWithAttribute <T>(this System.Type t, bool withInheritance = false) where T : Attribute { return (t.GetMethods() .Where(m => m.GetCustomAttributes(typeof(T), withInheritance).Length > 0) .ToArray()); }
/// <summary> /// 刷新VBA方法列表 /// </summary> protected void RefreshMethodList() { myVBAMethods.Clear(); System.Reflection.Assembly myAssembly = this.Assembly; foreach (object obj in this.Items) { if (obj is Microsoft.Vsa.IVsaCodeItem) { Microsoft.Vsa.IVsaCodeItem CodeItem = (Microsoft.Vsa.IVsaCodeItem)obj; System.Type t = myAssembly.GetType(this.RootNamespace + "." + CodeItem.Name); System.Reflection.MethodInfo[] ms = t.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); foreach (System.Reflection.MethodInfo m in ms) { VBAScriptMethodItem MethodItem = new VBAScriptMethodItem(); myVBAMethods.Add(MethodItem); MethodItem.ModuleName = CodeItem.Name; MethodItem.MethodName = m.Name; MethodItem.MethodObject = m; MethodItem.ReturnType = m.ReturnType; if (m.GetParameters().Length == 0) { System.Type dt = SlowAndSteadyParser.DelegateHelper.GetDelegateType(m.ReturnType); if (dt != null) { MethodItem.MethodDelegate = System.Delegate.CreateDelegate(dt, m); } } } //foreach } } }
public static PropertyDescriptorCollection GetMethodProperties(object obj) { System.Type type = obj.GetType(); if (obj is MethodPropertyDescriptor.MethodPropertyValueHolder) { MethodPropertyDescriptor.MethodPropertyValueHolder mobj = obj as MethodPropertyDescriptor.MethodPropertyValueHolder; // if ( mobj.Method.IsVoidMethdod ) // return null; return(mobj.Method.GetChildProperties(null, null)); } MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); ArrayList methodDesc = new ArrayList(); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; if (/*method.IsPublic &&*/ !method.IsSpecialName) { methodDesc.Add(new MethodPropertyDescriptor(obj, method)); } } methodDesc.Sort(new MethodNameComparer()); MethodPropertyDescriptor[] methodsDesc = (MethodPropertyDescriptor[])methodDesc.ToArray(typeof(MethodPropertyDescriptor)); return(new PropertyDescriptorCollection(methodsDesc)); }
internal static IEnumerable <Command> GetCommands(System.Type mytype) { var cmdsettype = typeof(CommandSet); if (!cmdsettype.IsAssignableFrom(mytype)) { string msg = String.Format("{0} must derive from {1}", mytype.Name, cmdsettype.Name); } var methods = mytype.GetMethods().Where(m => m.IsPublic && !m.IsStatic); foreach (var method in methods) { // Skip some method names switch (method.Name) { case "ToString": case "GetHashCode": case "GetType": case "Equals": continue; } var cmd = new Command(method); yield return(cmd); } }
/// <summary> /// Get public MethodInfos in a type. /// <param name="type">The type of the target object to get the methods.</param> /// <param name="staticMethods">If True returns only static members; otherwise returns instance members.</param> /// <returns>Public methods in a type.</returns> /// </summary> public static MethodInfo[] GetPublicMembers(System.Type type, bool staticMethods) { List <MethodInfo> methodInfos = new List <MethodInfo>(); BindingFlags bindingFlags = staticMethods ? BindingFlags.Public | BindingFlags.Static : BindingFlags.Public | BindingFlags.Instance; foreach (MethodInfo method in type.GetMethods(bindingFlags)) { Type returnType = method.ReturnParameter.ParameterType; if (returnType == typeof(void) || FunctionUtility.IsSupported(returnType)) { bool validParameters = true; foreach (ParameterInfo parameter in method.GetParameters()) { if (!FunctionUtility.IsSupported(parameter.ParameterType)) { validParameters = false; break; } } if (validParameters) { methodInfos.Add(method); } } } return(methodInfos.ToArray()); }
static void Main(string[] args) { //Reflection //Reflect Type //typeDef System.Type _typeDef = typeof(ReflectionDemo.A); //Check Flags System.Reflection.MethodInfo[] methods = _typeDef.GetMethods(); System.Reflection.ParameterInfo[] parameters = methods[0].GetParameters(); System.Reflection.FieldInfo[] feilds = _typeDef.GetFields(); System.Reflection.ConstructorInfo[] constructors = _typeDef.GetConstructors(); //for (int i = 0; i < methods.Length; i++) //{ // Console.WriteLine(methods[i].Name); //} System.Reflection.MethodInfo _funMethodMetadata = _typeDef.GetMethod("Fun", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //Dynamic Invoke _funMethodMetadata.Invoke(new A(), null); Object obj = new A(); System.Type _typeADef = obj.GetType();//returns metadata reference of object type _typeADef.GetMethod("Foo").Invoke(obj, null); System.Reflection.MethodInfo _concatMetadataRef = _typeADef.GetMethod("Concat"); object result = _concatMetadataRef.Invoke(obj, new object[] { 10, "Hello" }); }
private void ReadType(System.Type type) { const Ref::BindingFlags BF = Ref::BindingFlags.Static | Ref::BindingFlags.Public | Ref::BindingFlags.NonPublic; afh.Application.Log log = Program.log; log.WriteLine("ReadType: {0}", type.FullName); foreach (Ref::MethodInfo minfo in type.GetMethods(BF)) { // 超いい加減引数チェック if (TestMethod.IsTestable(minfo)) { TestMethod test = new TestMethod(minfo); test.WriteSummary(log); this.listBox1.Items.Add(test); } BenchMethodAttribute benchattr = BenchMethod.GetAttribute(minfo, log); if (benchattr != null) { BenchMethod bench = new BenchMethod(minfo, benchattr); this.listBox1.Items.Add(bench); } } }
public static List <Operator> Operators(System.Type type, bool addLogicOperators = false, bool noOverloads = true) { List <Operator> operators = new List <Operator>(); if (addLogicOperators) { operators.AddRange(logicOperators.Select(x => new Operator() { Name = x, Type = OperatorType.Logic })); } if (type == typeof(String)) { operators.AddRange(hardCodedStringOperators.Select(x => new Operator() { Name = x, Type = OperatorType.InternalString })); } else if (Member.IsSimpleType(type)) { operators.AddRange(comparisonOperators.Select(x => new Operator() { Name = x, Type = OperatorType.Comparison })); } var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (var method in methods) { if (method.ReturnType == typeof(Boolean) && !method.Name.StartsWith("get_") && !method.Name.StartsWith("set_") && !method.Name.StartsWith("_op")) { var paramaters = method.GetParameters(); var op = new Operator() { Name = method.Name, Type = OperatorType.ObjectMethod, NumberOfInputs = paramaters.Length, SimpleInputs = paramaters.All(x => Member.IsSimpleType(x.ParameterType)) }; if (noOverloads) { var existing = operators.FirstOrDefault(x => x.Name == op.Name && x.Type == op.Type); if (existing == null) { operators.Add(op); } else if (existing.NumberOfInputs > op.NumberOfInputs) { operators[operators.IndexOf(existing)] = op; } } else { operators.Add(op); } } } return(operators); }
public void LoadMethods(string methodNameString, List <string> listOfMethods) { Assembly[] referencedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies(); int referenceCount = referencedAssemblies.Length; int iterator = 0; while (iterator < referenceCount) { System.Type type = referencedAssemblies[iterator].GetType(methodNameString); if (type != null) { // I want all the declared methods from the specific class. System.Reflection.MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); int objectCount = methods.Length; int index = 0; char[] Seperators = new char[2]; Seperators[0] = ' '; Seperators[1] = '('; while (index < objectCount) { string[] listOfTempNameStrings = methods[index].ToString().Split(Seperators); listOfMethods.Add(listOfTempNameStrings[1]); index += 1; } return; } iterator += 1; } }
public static void DisposMethods(System.Type type, Dictionary <string, ClassMethodInfo> cmfDict) { BindingFlags options = BindingFlags | BindingFlags.Instance | BindingFlags.FlattenHierarchy; MethodInfo[] infoArray = type.GetMethods(options); foreach (MethodInfo info in infoArray) { if (info.IsGenericMethod) { continue; } if (info.Name.IndexOf('_') > 0) { continue; } string key = type.Namespace + "." + type.Name + "." + info.Name; ClassMethodInfo cmf = !cmfDict.ContainsKey(key)? new ClassMethodInfo() :cmfDict[key]; cmf.fullName = key; cmf.className = GetTypeName(type); cmf.name = info.Name; cmf.returnName = GetTypeName(info.ReturnType); cmf.isStatic = info.IsStatic; cmfDict[key] = cmf; cmf.overrideList.Add(DisposMethodArgs(info.GetParameters())); } }
private void ParseTestMethods(Type type) { foreach (MethodInfo methodInfo in type.GetMethods()) { this.ParseTestMethod(methodInfo); } }
public static bool IsAuthorizedForAction(string actionName, string controllerName) { bool isAuthorized = false; SystemType controller = SystemType.GetType(string.Format(ControllerIdentifier, controllerName)); if (controller != null) { MethodInfo[] mArr = controller.GetMethods().Where(mi => mi.Name == actionName).ToArray <MethodInfo>(); foreach (MethodInfo m in mArr) { RoleAttribute[] authTagList = m.GetCustomAttributes(typeof(RoleAttribute), true) as RoleAttribute[]; if (authTagList.Length < 1) { authTagList = controller.GetCustomAttributes(typeof(RoleAttribute), true) as RoleAttribute[]; } RoleEnum[] authTagArray = authTagList.Select(t => t.Role).ToArray <RoleEnum>(); SimpleUserModel currentUser = (SimpleUserModel)HttpContext.Current.Session["user"]; if (currentUser == null) { currentUser = new SimpleUserModel(); } isAuthorized = Authorize(currentUser, authTagArray); if (isAuthorized) { break; } } } return(isAuthorized); }
public static IFieldMiddlewareBuilder Use(this IFieldMiddlewareBuilder builder, System.Type middleware) { return(builder.Use(next => { var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public); var invokeMethods = methods.Where(m => string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)).ToArray(); if (invokeMethods.Length > 1) { throw new InvalidOperationException($"There should be only a single method named {InvokeMethodName}. Middleware actually has {invokeMethods.Length} methods."); } if (invokeMethods.Length == 0) { throw new InvalidOperationException($"Could not find a method named {InvokeMethodName}. Middleware must have a public instance method named {InvokeMethodName}."); } var methodInfo = invokeMethods[0]; if (!typeof(Task <object>).IsAssignableFrom(methodInfo.ReturnType)) { throw new InvalidOperationException($"The {InvokeMethodName} method should return a Task<object>."); } var parameters = methodInfo.GetParameters(); if (parameters.Length != 2 || parameters[0].ParameterType != typeof(ResolveFieldContext) || parameters[1].ParameterType != typeof(FieldMiddlewareDelegate)) { throw new InvalidOperationException($"The {InvokeMethodName} method of middleware should take a parameter of type {nameof(ResolveFieldContext)} as the first parameter and a parameter of type {nameof(FieldMiddlewareDelegate)} as the second parameter."); } var instance = Activator.CreateInstance(middleware); return context => (Task <object>)methodInfo.Invoke(instance, new object[] { context, next }); })); }
public void draw() { if (!_isSelected) { GUI.Box(_rect, "", _style); } else { GUI.Box(_rect, "", _selectedStyle); } GUI.Box(_iconRect, "", _iconStyle); GUI.Label(_parentLabelRect, "parent", _labelStyle); if (_nodeType == NodeType.Action || _nodeType == NodeType.Conditional) { if (GUI.Button(_functionInputRect, functionName + "()", _labelStyle)) { showFunctionsMenu(_scriptType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)); } GUI.Label(_functionLabelRect, "function:", _labelStyle); return; } GUI.Label(_childLabelRect, "childs", _labelStyle); }
/// <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 static MethodInfo UncachedGetImplicitConversionMethod(Type from, Type to) { return to.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static) .Where(x => x.Name == "op_Implicit") .Where(x => to.IsAssignableFrom(x.ReturnType)). FirstOrDefault(x => x.GetParameters().Single().ParameterType == @from); }
public static Type GenerateType(string dynamicTypeName, Type baseType, Type interfaceType) { TypeBuilder newType = _dynamicModule.DefineType( "Xunit.{Dynamic}." + dynamicTypeName, TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Class, baseType ); newType.AddInterfaceImplementation(interfaceType); foreach (MethodInfo interfaceMethod in interfaceType.GetMethods()) ImplementInterfaceMethod(newType, interfaceMethod); foreach (ConstructorInfo ctor in baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) switch (ctor.Attributes & MethodAttributes.MemberAccessMask) { case MethodAttributes.Family: case MethodAttributes.Public: case MethodAttributes.FamORAssem: ImplementConstructor(newType, ctor); break; } return newType.CreateType(); }
static IEnumerable<TestMethod> getTestableMethodsForType(Type type) { var typeAttributes = type.GetCustomAttributes(typeof (BitmapDrawingTestAttribute), inherit: false); var typeAttribute_ = typeAttributes.Length == 1 ? (BitmapDrawingTestAttribute) typeAttributes[0] : null; foreach (var method in type.GetMethods()) { var attributes = method.GetCustomAttributes(typeof (BitmapDrawingTestAttribute), inherit: false); switch (attributes.Length) { case 0: if (typeAttribute_ == null) break; yield return new TestMethod(method, typeAttribute_, ignorable: true); break; case 1: var attribute = (BitmapDrawingTestAttribute) attributes[0]; if (typeAttribute_ != null) attribute = typeAttribute_.refine(attribute); yield return new TestMethod(method, attribute, ignorable: false); break; } } }
public void ApplyMethods_MustBePublic(Type entityType) { //this just checks it has the attribute, at some point we might want to check if they actually are. entityType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance) .Count(m => m.Name == "Apply") .Should().Be(0, "Apply methods on entities should be public"); }
private void EnsureRelevantMethodsAreVirtual(Type service, Type implementation) { if (service.IsInterface) return; MethodInfo[] methods = implementation.GetMethods( BindingFlags.Instance|BindingFlags.Public|BindingFlags.DeclaredOnly ); ArrayList problematicMethods = new ArrayList(); foreach( MethodInfo method in methods ) { if (!method.IsVirtual && method.IsDefined( typeof(PermissionAttribute), true )) { problematicMethods.Add( method.Name ); } } if (problematicMethods.Count != 0) { String[] methodNames = (String[]) problematicMethods.ToArray( typeof(String) ); String message = String.Format( "The class {0} wants to use security interception, " + "however the methods must be marked as virtual in order to do so. Please correct " + "the following methods: {1}", implementation.FullName, String.Join(", ", methodNames) ); throw new FacilityException(message); } }
internal static InternalNodeViewCustomization Create(Type nodeModelType, Type customizerType) { if (nodeModelType == null) throw new ArgumentNullException("nodeModelType"); if (customizerType == null) throw new ArgumentNullException("customizerType"); // get the CustomizeView method appropriate to the supplied NodeModelType var methodInfo = customizerType.GetMethods() .Where(x => x.Name == "CustomizeView") .Where( x => { var firstParm = x.GetParameters().FirstOrDefault(); return firstParm != null && firstParm.ParameterType == nodeModelType; }).FirstOrDefault(); // if it doesn't exist, fail early if (methodInfo == null) { throw new Exception( "A CustomizeView method with type '" + nodeModelType.Name + "' does not exist on the supplied INodeViewCustomization type."); } return new InternalNodeViewCustomization(nodeModelType, customizerType, methodInfo); }
private static void RedirectMethods( System.Type type, System.Type targetType, Dictionary <MethodInfo, Redirector> redirects, bool onCreated) { foreach (MethodInfo method in ((IEnumerable <MethodInfo>)type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)).Where <MethodInfo>((Func <MethodInfo, bool>)(method => { object[] customAttributes = method.GetCustomAttributes(typeof(RedirectMethodAttribute), false); if (customAttributes.Length != 1) { return(false); } return(((RedirectMethodAttribute)customAttributes[0]).OnCreated == onCreated); }))) { Debug.Log((object)("Redirecting " + targetType.Name + "#" + method.Name + "...")); Redirector redirector = RedirectionUtil.RedirectMethod(targetType, method, redirects, false); FieldInfo field = type.GetField(method.Name + "Redirector", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.FieldType == typeof(Redirector)) { Debug.Log((object)"Redirector field found!"); field.SetValue((object)null, (object)redirector); } } }
internal void Init(MethodInfo mi, System.Type type) { int ct = 0; var ms = type.GetMethods(); foreach (var m in ms) { if (m.Name == mi.Name) { ++ct; } } if (ct > 1) { MethodName = CalcMethodMangling(mi); } else { MethodName = mi.Name; } var ps = mi.GetParameters(); ExistParam = ps.Length > 0; ExistReturnParam = false; foreach (var param in ps) { if (param.IsOut || param.ParameterType.IsByRef) { ExistReturnParam = true; break; } } }
public override void RefreshSchema(bool preferSilent) { try { this.SuppressDataSourceEvents(); Cursor current = Cursor.Current; try { Cursor.Current = Cursors.WaitCursor; System.Type type = GetType(base.Component.Site, this.TypeName, preferSilent); if (type != null) { MethodInfo[] methods = type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); MethodInfo info = null; MethodInfo info2 = null; bool flag = false; System.Type dataObjectType = null; if (!string.IsNullOrEmpty(this.ObjectDataSource.DataObjectTypeName)) { dataObjectType = GetType(base.Component.Site, this.ObjectDataSource.DataObjectTypeName, preferSilent); } foreach (MethodInfo info3 in methods) { if (string.Equals(info3.Name, this.SelectMethod, StringComparison.OrdinalIgnoreCase)) { if ((info2 != null) && (info2.ReturnType != info3.ReturnType)) { flag = true; } else { info2 = info3; } if (IsMatchingMethod(info3, this.SelectMethod, this.ObjectDataSource.SelectParameters, dataObjectType)) { info = info3; break; } } } if (((info == null) && (info2 != null)) && !flag) { info = info2; } if (info != null) { this.RefreshSchema(info.ReflectedType, info.Name, info.ReturnType, preferSilent); } } } finally { Cursor.Current = current; } } finally { this.ResumeDataSourceEvents(); } }
/// <summary> /// 得到一个类型中,所有标记为ControllerMethod的方法 /// </summary> /// <param name="type"></param> /// <returns></returns> private static ControllerInfo FindControllerMethods(System.Type type) { MethodInfo[] mis = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); List <ControllerMethodInfo> methodList = new List <ControllerMethodInfo>(); MethodInfo defaultMethod = null; foreach (MethodInfo mi in mis) { ControllerMethodAttribute cma = AttributeHelper.GetCustomAttribute <ControllerMethodAttribute>(mi); if (cma != null) { ControllerMethodInfo cmi = new ControllerMethodInfo(mi, cma.ForceIgnoreParameters); methodList.Add(cmi); if (defaultMethod == null && cma.Default) { defaultMethod = mi; } } } return(new ControllerInfo(methodList.ToArray(), defaultMethod)); }
/// <summary> /// Adds all members to the node's children, grabbing the parameters /// for methods. /// </summary> /// <param name="treeNode"></param> /// <param name="type"></param> private void addMembers(TreeNode treeNode, System.Type type) { // Get all members except methods MemberInfo[] memberInfo = type.GetMembers(); for (int j = 0; j < memberInfo.Length; j++) { if (memberInfo[j].ReflectedType.IsPublic && memberInfo[j].MemberType != MemberTypes.Method) { TreeNode node = treeNode.Nodes.Add(memberInfo[j].Name); node.Tag = memberInfo[j].MemberType; } } // Get all methods MethodInfo[] methodInfo = type.GetMethods(); for (int j = 0; j < methodInfo.Length; j++) { TreeNode node = treeNode.Nodes.Add(methodInfo[j].Name); string parms = ""; ParameterInfo[] parameterInfo = methodInfo[j].GetParameters(); for (int f = 0; f < parameterInfo.Length; f++) { parms += parameterInfo[f].ParameterType.ToString() + " " + parameterInfo[f].Name + ", "; } // Knock off remaining ", " if (parms.Length > 2) { parms = parms.Substring(0, parms.Length - 2); } node.Tag = parms; } }
internal static IEnumerable <MethodInfo> GetProxiableMethods(System.Type type) { const BindingFlags candidateMethodsBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; return(type.GetMethods(candidateMethodsBindingFlags).Where(m => m.IsProxiable())); }
/// <summary> /// Add a new Remote Creation Call. /// </summary> static void AddRCCs(object obj, System.Type type) { MethodInfo[] methods = type.GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); for (int b = 0; b < methods.Length; ++b) { if (methods[b].IsDefined(typeof(RCC), true)) { RCC tnc = (RCC)methods[b].GetCustomAttributes(typeof(RCC), true)[0]; for (int i = 0; i < mRCCs.size; ++i) { CachedFunc f = mRCCs[i]; if (f.id == tnc.id) { f.obj = obj; f.func = methods[b]; return; } } CachedFunc ent = new CachedFunc(); ent.obj = obj; ent.func = methods[b]; ent.id = tnc.id; mRCCs.Add(ent); } } }
private void Test(Type type, string name, Type[] args, Type ethalonType) { var res = new ExtensionMethodResolver(new Dictionary<string, bool> {{"System", true}, {"System.Linq", true}}); var found = res.FindExtensionMethod(type, name, args); var bucket = ethalonType.GetMethods().Where(m => m.Name == name).ToArray(); Assert.Contains(found, bucket); }
/// <summary> /// Constructor /// </summary> private Reflection(System.Type type) { this.Type = type; this.Interfaces = new ReadOnlyCollection <System.Type>(type.GetInterfaces()); this.PropertyInfos = new ReadOnlyCollection <PropertyInfo>(type.GetProperties()); var propDic = new Dictionary <string, Property>(); foreach (var property in this.PropertyInfos) { var xbProp = Property.Get(property); propDic.Add(property.Name, xbProp); } this.Properties = new ReadOnlyDictionary <string, Property>(propDic); this.Constructors = new ReadOnlyCollection <ConstructorInfo>(type.GetConstructors()); this.MethodInfos = new ReadOnlyCollection <MethodInfo>(type.GetMethods()); var methodDic = new Dictionary <MethodInfo, ReadOnlyCollection <ParameterInfo> >(); foreach (var method in this.MethodInfos) { methodDic.Add(method, new ReadOnlyCollection <ParameterInfo>(method.GetParameters())); } this.MethodParameters = new ReadOnlyDictionary <MethodInfo, ReadOnlyCollection <ParameterInfo> >(methodDic); this.EventInfos = new ReadOnlyCollection <EventInfo>(type.GetEvents()); this.FieldInfos = new ReadOnlyCollection <FieldInfo>(type.GetFields()); }
protected override JsTypeDefinition OnBuildRequest(Type t) { //find member that has JsPropertyAttribute or JsMethodAttribute JsTypeDefinition typedefinition = new JsTypeDefinition(t.Name); //only instance /public method /prop*** var methods = t.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); foreach (var met in methods) { var customAttrs = met.GetCustomAttributes(typeOfJsMethodAttr, false); if (customAttrs != null && customAttrs.Length > 0) { var attr = customAttrs[0] as JsMethodAttribute; typedefinition.AddMember(new JsMethodDefinition(attr.Name ?? met.Name, met)); } } var properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); foreach (var property in properties) { var customAttrs = property.GetCustomAttributes(typeOfJsPropertyAttr, false); if (customAttrs != null && customAttrs.Length > 0) { var attr = customAttrs[0] as JsPropertyAttribute; typedefinition.AddMember(new JsPropertyDefinition(attr.Name ?? property.Name, property)); } } return typedefinition; }
private static void ProcessStaticMethodAttributes(System.Type type) { List <string> methodNames = null; List <RuntimeInitializeLoadType> loadTypes = null; MethodInfo[] methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); for (int i = 0; i < methods.GetLength(0); i++) { MethodInfo element = methods[i]; if (Attribute.IsDefined(element, typeof(RuntimeInitializeOnLoadMethodAttribute))) { RuntimeInitializeLoadType afterSceneLoad = RuntimeInitializeLoadType.AfterSceneLoad; object[] customAttributes = element.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), false); if ((customAttributes != null) && (customAttributes.Length > 0)) { afterSceneLoad = ((RuntimeInitializeOnLoadMethodAttribute)customAttributes[0]).loadType; } if (methodNames == null) { methodNames = new List <string>(); loadTypes = new List <RuntimeInitializeLoadType>(); } methodNames.Add(element.Name); loadTypes.Add(afterSceneLoad); } if (Attribute.IsDefined(element, typeof(InitializeOnLoadMethodAttribute))) { element.Invoke(null, null); } } if (methodNames != null) { StoreRuntimeInitializeClassInfo(type, methodNames, loadTypes); } }
public UpshotControllerDescription(HttpControllerDescriptor controllerDescriptor) { HashSet<Type> entityTypes = new HashSet<Type>(); _upshotControllerType = controllerDescriptor.ControllerType; IEnumerable<MethodInfo> enumerable = from p in _upshotControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public) where p.DeclaringType != typeof(UpshotController) && p.DeclaringType != typeof(object) && !p.IsSpecialName select p; foreach (MethodInfo current in enumerable) { if (current.GetCustomAttributes(typeof(NonActionAttribute), false).Length <= 0 && (!current.IsVirtual || !(current.GetBaseDefinition().DeclaringType == typeof(UpshotController)))) { if (current.ReturnType != typeof(void)) { Type type = TypeUtility.UnwrapTaskInnerType(current.ReturnType); Type elementType = TypeUtility.GetElementType(type); if (LookUpIsEntityType(elementType)) { if (!entityTypes.Contains(elementType)) { entityTypes.Add(elementType); } } } } } _entityTypes = new ReadOnlyCollection<Type>(entityTypes.ToList()); }
public void RegClass(System.Type klass, string macro, ECSType csType) { if (klass.IsGenericType) { return; } var methods = klass.GetMethods(); foreach (var i in methods) { var rpcAttr = Rtti.AttributeHelper.GetCustomAttribute(i, typeof(RPCCallAttribute).FullName, true); if (rpcAttr == null) { continue; } var args = i.GetParameters(); var proc_type = GetRPCMethodProcessor(args); if (proc_type == null) { Profiler.Log.WriteLine(Profiler.ELogTag.Warning, "RPC", $"Method: {i.DeclaringType.FullName}.{i.Name} arguments is not valid"); continue; } var type = Rtti.RttiHelper.GetTypeFromTypeFullName(proc_type.FullName, csType); //var atts = type.GetCustomAttributes(typeof(RPCProcessorAttribute), false); //if (atts == null || atts.Length == 0) // continue; //var senderDesc = atts[0] as RPCProcessorAttribute; //var sender = RPCProcessor.InitProcessor(senderDesc.ProcessorType, type, senderDesc.ReturnType); var sender = RPCProcessor.GetProcessorByArgument(type); RegRPC(sender, i, type, macro); } }
public DynamicComObjectWrapper(COMRegistry registry, Type instanceType, object entry) { _registry = registry; if (instanceType == null) { throw new ArgumentNullException("instanceType"); } if (entry == null) { throw new ArgumentNullException("entry"); } if (!COMUtilities.IsComImport(instanceType)) { throw new ArgumentException("Interface type must be an imported COM type"); } if (!Marshal.IsComObject(entry)) { throw new ArgumentException("Target must be a COM object"); } _methods = instanceType.GetMethods().Where(m => !m.IsSpecialName).ToDictionary(m => m.Name); _properties = instanceType.GetProperties().ToDictionary(m => m.Name); _target = entry; _instanceType = instanceType; }
/// <summary> /// Rebuild the list of known RFC calls. /// </summary> void RebuildMethodList() { rebuildMethodList = false; mRFCs.Clear(); MonoBehaviour[] mbs = GetComponentsInChildren <MonoBehaviour>(true); for (int i = 0, imax = mbs.Length; i < imax; ++i) { MonoBehaviour mb = mbs[i]; System.Type type = mb.GetType(); MethodInfo[] methods = type.GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int b = 0; b < methods.Length; ++b) { if (methods[b].IsDefined(typeof(RFC), true)) { CachedFunc ent = new CachedFunc(); ent.obj = mb; ent.func = methods[b]; RFC tnc = (RFC)ent.func.GetCustomAttributes(typeof(RFC), true)[0]; ent.id = tnc.id; mRFCs.Add(ent); } } } }
public DynamicProxyBase(Type ProxyType, object ConcreteObjectProxy) { this.ConcreteObjectProxy = ConcreteObjectProxy; this.MethodInterceptorRegistrations = new Dictionary<MethodInfo, IList<IInterceptor>>(); this.PropertyInterceptorRegistrations = new Dictionary<PropertyInfo, IList<IPropertyInterceptor>>(); // read interceptor registrations from Registration Service. var registraton = InterceptorRegistrationService.Resolve(ProxyType); if (!(registraton is EmptyInterceptorRegistration)) { var properties = ProxyType.GetProperties(); var methods = ProxyType.GetMethods(); foreach (var prop in properties) { var propInterceptors = registraton.GetPropertyInterceptors(prop.Name); if (propInterceptors != null) this.PropertyInterceptorRegistrations.Add(prop, propInterceptors); } foreach (var method in methods) { var methodInterceptors = registraton.GetMethodInterceptors(method.Name); if (methodInterceptors != null) this.MethodInterceptorRegistrations.Add(method, methodInterceptors); } } }
internal static MethodInfo GetMethodExactMatch(System.Type type, string name, BindingFlags bindingAttr, Binder binder, System.Type[] types, ParameterModifier[] modifiers) { foreach (MethodInfo info2 in type.GetMethods(bindingAttr)) { if (((bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase) ? (string.Compare(info2.Name, name, StringComparison.OrdinalIgnoreCase) == 0) : (string.Compare(info2.Name, name, StringComparison.Ordinal) == 0)) { bool flag2 = false; if (types != null) { ParameterInfo[] parameters = info2.GetParameters(); if (parameters.GetLength(0) == types.Length) { for (int i = 0; !flag2 && (i < parameters.Length); i++) { flag2 = (parameters[i].ParameterType == null) || !parameters[i].ParameterType.IsAssignableFrom(types[i]); } } else { flag2 = true; } } if (!flag2) { return(info2); } } } return(null); }
public static string[] getMethodOptions(GameObject comp, List <System.Type> ignoreTypes = null) { List <string> methods = new List <string>(); if (comp != null) { Component[] allComponents = comp.GetComponents <Component>(); List <System.Type> doneTypes = new List <System.Type>(); for (int index = 0; index < allComponents.Length; index++) { System.Type compType = allComponents[index].GetType(); if (!doneTypes.Contains(compType) && (ignoreTypes == null || !ignoreTypes.Contains(compType))) { MethodInfo[] allMemebers = compType.GetMethods(); for (int memberIndex = 0; memberIndex < allMemebers.Length; memberIndex++) { if (allMemebers[memberIndex].IsPublic && allMemebers[memberIndex].GetParameters().Length == 0 && !methods.Contains(allMemebers[memberIndex].Name) && allMemebers[memberIndex].ReturnType == typeof(void)) { methods.Add(allMemebers[memberIndex].Name); } } doneTypes.Add(compType); } } } return(methods.ToArray()); }
private void invocarMetodosDataAccessGet(ref System.Data.DataSet dtSet) { try { m_cls_dba_ConectionDB.FonteDosDados = mdlDataBaseAccess.FonteDados.DataBase; Object[] ObjParametros = { null, null, null, null, null }; Object retorno = null; System.Data.DataTable tabelaTemp = null; System.Type typDB = (typeof(mdlDataBaseAccess.clsDataBaseAccess)); System.Reflection.MethodInfo[] mtInfoTempArray = typDB.GetMethods(); foreach (System.Reflection.MethodInfo mtInfo in mtInfoTempArray) { if ((!m_bIncluirModulos) && (mtInfo.Name == "GetTbModulos")) { continue; } if (mtInfo.Name.StartsWith("GetTb")) { m_cls_dba_ConectionDB.FonteDosDados = mdlDataBaseAccess.FonteDados.DataBase; retorno = mtInfo.Invoke(m_cls_dba_ConectionDB, ObjParametros); tabelaTemp = ((System.Data.DataSet)retorno).Tables[0]; ((System.Data.DataSet)retorno).Tables.RemoveAt(0); dtSet.Tables.Add(tabelaTemp); } } } catch (Exception err) { m_cls_ter_tratadorErro.trataErro(ref err); } }