/// <summary> /// Reads all fields with the specified binding of the object in alphabetical order using reflection /// </summary> public void ReadAllProperties(object target, BindingFlags flags) { if (target == null) throw new ArgumentNullException("target"); Type tp = target.GetType(); PropertyInfo[] fields = tp.GetProperties(flags); NetUtility.SortMembersList(fields); foreach (PropertyInfo fi in fields) { object value; // find read method MethodInfo readMethod; if (s_readMethods.TryGetValue(fi.PropertyType, out readMethod)) { // read value value = readMethod.Invoke(this, null); // set the value #if UNITY_WEBPLAYER || UNITY_4_5 var setMethod = fi.GetSetMethod(); #else //This must be changed to the above as this cannot be done in .Net 3.5 //Reflection is not too fancy in 3.5 //Previous: var setMethod = fi.SetMethod; var setMethod = fi.GetSetMethod(); #endif if (setMethod != null) setMethod.Invoke(target, new object[] { value }); } } }
public static FieldInfo[] GetFields(this Type type, BindingFlags bindingAttr) { return type.GetRuntimeFields() .Where(fieldInfo => AreBindingFlagsMatching(fieldInfo, bindingAttr)) .ToArray(); }
/// <summary> /// Reads all fields with the specified binding of the object in alphabetical order using reflection /// </summary> public void ReadAllProperties(object target, BindingFlags flags) { if (target == null) throw new ArgumentNullException("target"); Type tp = target.GetType(); PropertyInfo[] fields = tp.GetProperties(flags); NetUtility.SortMembersList(fields); foreach (PropertyInfo fi in fields) { object value; // find read method MethodInfo readMethod; if (s_readMethods.TryGetValue(fi.PropertyType, out readMethod)) { // read value value = readMethod.Invoke(this, null); // set the value //#if UNITY_WEBPLAYER || UNITY_4_5 // var setMethod = fi.GetSetMethod(); //#else //var setMethod = fi.SetMethod; //#endif var setMethod = fi.GetSetMethod(); if (setMethod != null) setMethod.Invoke(target, new object[] { value }); } } }
private static bool IsMatch(PropertyInfo propertyInfo, BindingFlags flags) { // this methods is heavily used during reflection, so we have traded // readablility for performance. var mainMethod = propertyInfo.GetGetMethod() ?? propertyInfo.GetSetMethod(); if (mainMethod == null) return false; if (flags == Type.BindFlags.AllMembers || flags == Type.BindFlags.DeclaredMembers) return true; bool incStatic = (flags & BindingFlags.Static) == BindingFlags.Static; bool incInstance = (flags & BindingFlags.Instance) == BindingFlags.Instance; if (incInstance == incStatic && !incInstance) return false; if (incInstance != incStatic) { bool isStatic = mainMethod.IsStatic; if (!((incStatic && isStatic) || (incInstance && !isStatic))) return false; } bool incPublic = (flags & BindingFlags.Public) == BindingFlags.Public; bool incNonPublic = (flags & BindingFlags.NonPublic) == BindingFlags.NonPublic; if (incPublic == incNonPublic) return incPublic; bool isPublic = mainMethod.IsPublic; return (incPublic && isPublic) || (incNonPublic && !isPublic); }
public Object InvokeMember(String name, BindingFlags flags, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo locale, String[] namedParameters){ if ((flags & BindingFlags.CreateInstance) == 0) //Try to create an instance of the array return LateBinding.CallValue(this.elementType, args, true, true, null, null, binder, locale, namedParameters); return Typeob.Array.InvokeMember(name, flags, binder, target, args, modifiers, locale, namedParameters); }
public void TestShouldSelectWithDifferentConstructors(string description, BindingFlags flags, bool shouldSelect) { var constructor = new AnalysisDataResolver().Resolve(this.GetType().GetConstructors(flags)[0]); bool result = new TestableStaticConstructorsSelectionStrategy().ShouldSelect(constructor, null); Assert.AreEqual(shouldSelect, result); }
/// <summary> /// Reads all fields with the specified binding of the object in alphabetical order using reflection /// </summary> public void ReadAllFields(object target, BindingFlags flags) { if (target == null) throw new ArgumentNullException("target"); Type tp = target.GetType(); FieldInfo[] fields = tp.GetFields(flags); NetUtility.SortMembersList(fields); foreach (FieldInfo fi in fields) { object value; // find read method MethodInfo readMethod; if (s_readMethods.TryGetValue(fi.FieldType, out readMethod)) { // read value value = readMethod.Invoke(this, null); // set the value fi.SetValue(target, value); } } }
protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(name != null); if (!OnlySearchRelatedBitsSet(bindingAttr)) // We don't yet have proper handling for BindingFlags not related to search so throw rather return a wrong result. throw new NotImplementedException(); // GetPropertyImpl() is a funnel for two groups of api. We can distinguish by comparing "types" to null. if (types == null && returnType == null) { // Group #1: This group of api accept only a name and BindingFlags. The other parameters are hard-wired by the non-virtual api entrypoints. Debug.Assert(binder == null); Debug.Assert(modifiers == null); return LowLevelTypeExtensions.GetProperty(this, name, bindingAttr); } else { if (!OnlySearchRelatedBitsSet(bindingAttr)) // We don't yet have proper handling for BindingFlags not related to search so throw rather return a wrong result. throw new NotImplementedException(); // Group #2: This group of api takes a set of parameter types, a return type (both cannot be null) and an optional binder. if (binder == null) binder = Type.DefaultBinder; PropertyInfo[] candidates = LowLevelTypeExtensions.GetProperties(this, name, bindingAttr); return binder.SelectProperty(bindingAttr, candidates, returnType, types, modifiers); } }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo locale){ if (obj is StackFrame){ this.field.SetValue(((StackFrame)((StackFrame)obj).engine.ScriptObjectStackTop()).closureInstance, value, invokeAttr, binder, locale); return; } throw new JScriptException(JSError.InternalError); //should never happen }
/// <summary> /// Reads all fields with the specified binding of the object in alphabetical order using reflection /// </summary> public void ReadAllProperties(object target, BindingFlags flags) { if (target == null) throw new ArgumentNullException("target"); if (target == null) return; Type tp = target.GetType(); PropertyInfo[] fields = tp.GetProperties(flags); NetUtility.SortMembersList(fields); foreach (PropertyInfo fi in fields) { object value; // find read method MethodInfo readMethod; if (s_readMethods.TryGetValue(fi.PropertyType, out readMethod)) { // read value value = readMethod.Invoke(this, null); // set the value MethodInfo setMethod = fi.GetSetMethod((flags & BindingFlags.NonPublic) == BindingFlags.NonPublic); setMethod.Invoke(target, new object[] { value }); } } }
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance1"]/*' /> static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) { if (type == null) throw new ArgumentNullException("type"); if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(Environment.GetResourceString( "NotSupported_CreateInstanceWithTypeBuilder" )); // If they didn't specify a lookup, then we will provide the default lookup. if ((bindingAttr & (BindingFlags) LookupMask) == 0) bindingAttr |= Activator.ConstructorDefault; try { RuntimeType rt = (RuntimeType) type.UnderlyingSystemType; return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes); } catch (InvalidCastException) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type"); } }
private static object RunMethod(System.Type t, string methodName, object objInstance, BindingFlags eFlags, System.Type[] parameterDefinitions, object[] parameterValues) { foreach (MethodInfo m in t.GetMethods(eFlags)) { if (m.Name == methodName && MethodMatchesParameterDefinitions(m, parameterDefinitions)) { if (parameterDefinitions.Length == parameterValues.Length + 1) { throw new NotImplementedException("The case in which no args are passed to params parameter."); } // if only parameter is params arg, compiler collapses it. this re-expands it: else if (parameterDefinitions[parameterDefinitions.Length - 1] != parameterValues[parameterValues.Length - 1].GetType()) { Array unknownTypeArray = Array.CreateInstance(parameterValues[0].GetType(), parameterValues.Length); parameterValues.CopyTo(unknownTypeArray, 0); return m.Invoke(objInstance, new object[] { unknownTypeArray }); } else { return m.Invoke(objInstance, parameterValues); } } } throw new ArgumentException("There is no method '" + methodName + "' for type '" + t.ToString() + "' which matched the parameter type list."); }
/// <summary> /// Gets a method. /// </summary> /// <param name="t"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="p1"></param> /// <param name="parameterTypes"></param> /// <param name="p2"></param> /// <returns></returns> public static System.Reflection.MethodInfo GetMethod(this Type t, string methodName, BindingFlags flags, object p1, Type[] parameterTypes, object p2) { var ti = t.GetTypeInfo(); System.Reflection.MethodInfo result = null; while (ti != null) { var potentials = ti.DeclaredMethods. Where(r => r.Name == methodName && r.GetParameters().Count() == parameterTypes.Count()); foreach (var item in potentials) { result = item; var resultParameters = result.GetParameters(); for (int i = 0; i < resultParameters.Count(); i++) { if (resultParameters[i].ParameterType != parameterTypes[i]) { result = null; break; } } if (result != null) break; } if (result != null) break; if (ti.BaseType == null) break; ti = ti.BaseType.GetTypeInfo(); } return result; }
public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { int matchCount = 0; foreach (MethodBase method in match) { if (MatchParameterTypes(method.GetParameters(), types)) { match[matchCount++] = method; } } if (matchCount == 0) { return null; } MethodBase bestMatch = match[0]; bool ambiguous = false; for (int i = 1; i < matchCount; i++) { SelectBestMatch(match[i], types, ref bestMatch, ref ambiguous); } if (ambiguous) { throw new AmbiguousMatchException(); } return bestMatch; }
public override MethodBase SelectMethod( BindingFlags bindingAttr, MethodBase[] matchMethods, Type[] parameterTypes, ParameterModifier[] modifiers) { for (int i = 0; i < matchMethods.Length; ++i) { if (matchMethods[i].IsGenericMethodDefinition == _genericMethodDefinition) { ParameterInfo[] pis = matchMethods[i].GetParameters(); bool match = (pis.Length == parameterTypes.Length); for (int j = 0; match && j < pis.Length; ++j) { if (pis[j].ParameterType == parameterTypes[j]) continue; if (pis[j].ParameterType.IsGenericParameter) match = CheckGenericTypeConstraints(pis[j].ParameterType, parameterTypes[j]); else if (pis[j].ParameterType.IsGenericType && parameterTypes[j].IsGenericType) match = CompareGenericTypesRecursive(pis[j].ParameterType, parameterTypes[j]); else match = false; } if (match) return matchMethods[i]; } } return null; }
public Func( object target, string methodName, object[] args, BindingFlags bindingFlags ) { _target = target; _methodName = methodName; _methodInfo = _target.GetType().GetMethod( _methodName, bindingFlags ); _args = args; }
/// <summary> /// Gets the fields. /// </summary> /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param> /// <param name="bindingFlags">The binding flags.</param> /// <returns>An array of <see cref="FieldInfo"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="typeInfo"/> is <c>null</c>.</exception> public static FieldInfo[] GetFields(this TypeInfo typeInfo, BindingFlags bindingFlags) { Argument.IsNotNull("typeInfo", typeInfo); var flattenHierarchy = ShouldFlattenHierarchy(bindingFlags); var source = flattenHierarchy ? typeInfo.AsType().GetRuntimeFields().ToList() : typeInfo.DeclaredFields.ToList(); var includeStatics = Enum<BindingFlags>.Flags.IsFlagSet(bindingFlags, BindingFlags.Static); // TODO: This is a fix because static members are not included in FlattenHierarcy, remove when this is fixed in WinRT if (flattenHierarchy) { var baseType = typeInfo.BaseType; if ((baseType != null) && (baseType != typeof(object))) { source.AddRange(from member in GetFields(baseType.GetTypeInfo(), bindingFlags) where member.IsStatic select member); } } if (!includeStatics) { source = (from x in source where !x.IsStatic select x).ToList(); } return (from x in source where x.IsStatic == includeStatics select x).ToArray(); }
public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { Type[] args = new Type[parameters.Length]; for (var i = 0; i < args.Length; i++) args[i] = parameters[i] as Type; return TypeProxy.GetConstructor(target.MakeGenericType(args)); }
public static IEnumerable<ConstructorInfo> GetConstructors(this Type type, BindingFlags flags) { return type.GetConstructors() .Where(m => (flags & BindingFlags.Public) != BindingFlags.Public || m.IsPublic) .Where(m => (flags & BindingFlags.Instance) != BindingFlags.Instance || !m.IsStatic) .Where(m => (flags & BindingFlags.Static) != BindingFlags.Static || m.IsStatic); }
static FieldInfo GetField(Type type, Type fieldType, BindingFlags flags) { foreach (var field in type.GetFields(flags)) { if (field.FieldType == fieldType) return field; } return null; }
static FieldInfo GetField(Type type, string fieldName, BindingFlags flags) { foreach (var field in type.GetFields(flags)) { if (field.Name == fieldName) return field; } return null; }
internal void AddOverloadedMembers(MemberInfoList mems, ClassScope scope, BindingFlags attrs){ JSMemberField field = this; while (field != null){ MethodInfo meth = ((JSMemberField)field).GetAsMethod(scope); if (meth.IsStatic){ if ((attrs & BindingFlags.Static) == 0) goto next; }else{ if ((attrs & BindingFlags.Instance) == 0) goto next; } if (meth.IsPublic){ if ((attrs & BindingFlags.Public) == 0) goto next; }else{ if ((attrs & BindingFlags.NonPublic) == 0) goto next; } mems.Add(meth); next: field = field.nextOverload; } if ((attrs & BindingFlags.DeclaredOnly) != 0 && (attrs&BindingFlags.FlattenHierarchy) == 0) return; IReflect superClass = scope.GetSuperType(); MemberInfo[] supMembers = superClass.GetMember(this.Name, attrs&~BindingFlags.DeclaredOnly); foreach (MemberInfo supMember in supMembers) if (supMember.MemberType == MemberTypes.Method) mems.Add(supMember); }
/// <summary> /// Validate and get the list of properties specified by this attribute on the given type. /// </summary> /// <param name="type">clr type on which this attribute must have defined.</param> /// <param name="inherit">whether we need to inherit this attribute or not. /// For context types,we need to, since we can have one context dervied from another, and we want to ignore all the properties on the base ones too. /// For resource types, we don't need to, since we don't want derived types to know about ignore properties of the base type. Also /// from derived type, you cannot change the definition of the base type.</param> /// <param name="bindingFlags">binding flags to be used for validating property names.</param> /// <returns>list of property names specified on IgnoreProperties on the given type.</returns> internal static IEnumerable<string> GetProperties(Type type, bool inherit, BindingFlags bindingFlags) { IgnorePropertiesAttribute[] attributes = (IgnorePropertiesAttribute[])type.GetCustomAttributes(typeof(IgnorePropertiesAttribute), inherit); Debug.Assert(attributes.Length == 0 || attributes.Length == 1, "There should be atmost one IgnoreProperties specified"); if (attributes.Length == 1) { foreach (string propertyName in attributes[0].PropertyNames) { if (String.IsNullOrEmpty(propertyName)) { throw new InvalidOperationException(Strings.IgnorePropertiesAttribute_PropertyNameCannotBeNullOrEmpty); } PropertyInfo property = type.GetProperty(propertyName, bindingFlags); if (property == null) { throw new InvalidOperationException(Strings.IgnorePropertiesAttribute_InvalidPropertyName(propertyName, type.FullName)); } } return attributes[0].PropertyNames; } return WebUtil.EmptyStringArray; }
public override MethodBase SelectMethod( BindingFlags bindingAttr, MethodBase[] matchMethods, Type[] parameterTypes, ParameterModifier[] modifiers) { for (int i = 0; i < matchMethods.Length; ++i) { if (matchMethods[i].IsGenericMethodDefinition != _genericMethodDefinition) continue; ParameterInfo[] pis = matchMethods[i].GetParameters(); bool match = (pis.Length == parameterTypes.Length); for (int j = 0; match && j < pis.Length; ++j) { match = TypeHelper.CompareParameterTypes(pis[j].ParameterType, parameterTypes[j]); } if (match) return matchMethods[i]; } return null; }
public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state ) { for (int i = 0; i < args.Length; i++) { if (args[i] is string) { args[i] = ChangeType(args[i], typeof(string), culture); } if (args[i] is int) { args[i] = ChangeType(args[i], typeof(int), culture); } if (args[i] is bool) { args[i] = ChangeType(args[i], typeof(bool), culture); } } return Type.DefaultBinder.BindToMethod( bindingAttr, match, ref args, modifiers, culture, names, out state ); }
public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state) { if (match == null) { throw new ArgumentNullException("match"); } // Arguments are not being reordered. state = null; // Find a parameter match and return the first method with // parameters that match the request. foreach (MethodBase mb in match) { ParameterInfo[] parameters = mb.GetParameters(); if (ParametersMatch(parameters, args)) { return mb; } } return null; }
public override FieldInfo BindToField(BindingFlags bindAttr, FieldInfo[] match, object value, CultureInfo locale) { if (value == null) { value = DBNull.Value; } int num = 0x7fffffff; int num2 = 0; FieldInfo info = null; Type actual = value.GetType(); int index = 0; int length = match.Length; while (index < length) { FieldInfo info2 = match[index]; int num5 = TypeDistance(Runtime.TypeRefs, info2.FieldType, actual); if (num5 < num) { num = num5; info = info2; num2 = 0; } else if (num5 == num) { num2++; } index++; } if (num2 > 0) { throw new AmbiguousMatchException(); } return info; }
private object[] ExecutePosTest( CustomAttributeBuilder customAttrBuilder, MethodAttributes getMethodAttr, Type returnType, Type[] paramTypes, BindingFlags bindingAttr) { TypeBuilder myTypeBuilder = GetTypeBuilder(TypeAttributes.Class | TypeAttributes.Public); PropertyBuilder myPropertyBuilder = myTypeBuilder.DefineProperty(DynamicPropertyName, PropertyAttributes.HasDefault, returnType, null); myPropertyBuilder.SetCustomAttribute(customAttrBuilder); // Define the "get" accessor method for DynamicPropertyName MethodBuilder myMethodBuilder = myTypeBuilder.DefineMethod(DynamicMethodName, getMethodAttr, returnType, paramTypes); ILGenerator methodILGenerator = myMethodBuilder.GetILGenerator(); methodILGenerator.Emit(OpCodes.Ldarg_0); methodILGenerator.Emit(OpCodes.Ret); // Map the 'get' method created above to our PropertyBuilder myPropertyBuilder.SetGetMethod(myMethodBuilder); Type myType = myTypeBuilder.CreateTypeInfo().AsType(); PropertyInfo myProperty = myType.GetProperty(DynamicPropertyName, bindingAttr); return myProperty.GetCustomAttributes(false).Select(a => (object)a).ToArray(); }
public static object ExecuteMethod(Type type, string methodName, object instance, object[] methodParams, BindingFlags bindingFlags) { MethodInfo targetMethod = null; var methods = type.GetMethods(bindingFlags); var namedMethods = methods.Where(_ => _.Name == methodName && _.GetParameters().Count() == methodParams.Count()); foreach (var namedMethod in namedMethods) { var found = true; for (var i = 0; i < namedMethod.GetParameters().Count(); i++) { if (namedMethod.GetParameters()[i].GetType().IsInstanceOfType(methodParams[i])) { found = false; } } if (found) { targetMethod = namedMethod; } } return targetMethod == null ? null : targetMethod.Invoke(instance, methodParams); }
private static MethodRecognitionResult FindValidMethodOveloads(Type type, string name, BindingFlags flags, Type[] typeArguments, Expression[] arguments, IDictionary<string, Expression> namedArgs) { var methods = FindValidMethodOveloads(type.GetMethods(flags).Where(m => m.Name == name), typeArguments, arguments, namedArgs); var method = methods.FirstOrDefault(); if (method == null) throw new InvalidOperationException($"Could not find overload of method '{name}'."); return method; }
private void GetChildPrivateFields(IList <MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable <FieldInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate); initialFields.AddRange(childPrivateFields); } } }
public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList <Type> parameterTypes, object placeholder2) { return(type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault()); }
public static IEnumerable <ConstructorInfo> GetConstructors(this Type type, BindingFlags bindingFlags) { return(type.GetConstructors(bindingFlags, null)); }
public static IEnumerable <MemberInfo> GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetMembersRecursive().Where(m => { if (name != null && name != m.Name) { return false; } if (m.MemberType() != memberType) { return false; } if (!TestAccessibility(m, bindingFlags)) { return false; } return true; })); }
public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetDeclaredMethod(name)); }
public static IEnumerable <MemberInfo> GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingFlags) { return(type.GetMembers(bindingFlags).Where(m => { if (name != null && name != m.Name) { return false; } if (m.MemberType() != memberType) { return false; } return true; })); }
public IEnumerable <MethodInfo> GetMethods(Type type, BindingFlags bindingFlags) { return(XTypesBasic.Api.GetMethods(type, bindingFlags)); }
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetDeclaredProperty(name)); }
public static IEnumerable <PropertyInfo> GetProperties(this Type type, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetPropertiesRecursive().Where(p => TestAccessibility(p, bindingFlags))); }
public static IEnumerable <FieldInfo> GetFields(this Type type, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetFieldsRecursive().Where(f => TestAccessibility(f, bindingFlags)).ToList()); }
public static MemberInfo[] GetMember(this Type type, string member, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetMembersRecursive().Where(m => m.Name == member && TestAccessibility(m, bindingFlags)).ToArray()); }
public static IEnumerable <MethodInfo> GetMethods(this Type type, BindingFlags bindingFlags) { return(type.GetTypeInfo().DeclaredMethods); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="help"></param> /// <param name="propertyFalg">属性继承</param> /// <returns></returns> public static PropertyInfo[] GetEntityProperty <T>(this T help, BindingFlags propertyFalg) where T : class { return(help.GetType().GetProperties(propertyFalg)); }
public static MemberInfo GetField(this Type type, string member, BindingFlags bindingFlags) { return(type.GetTypeInfo().GetDeclaredField(member)); }
/// <inheritdoc /> protected override IEnumerable <Test> GetContractVerificationTests() { const BindingFlags bindingCommon = BindingFlags.InvokeMethod | BindingFlags.Public; const BindingFlags bindingPublicInstance = bindingCommon | BindingFlags.Instance; const BindingFlags bindingAllInstance = bindingPublicInstance | BindingFlags.NonPublic; const BindingFlags bindingAllStatic = bindingCommon | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy; // Is Object equality method OK? yield return(CreateEqualityTest(new EqualitySpecifications { Name = "ObjectEquals", MethodFriendlyName = "bool Equals(Object)", ExpectedEquality = true, GetWorkingType = o => o.GetType(), GetEqualityMethod = t => t.GetMethod("Equals", bindingPublicInstance, null, new[] { typeof(object) }, null), IsEqualityMethodRequired = o => true, IsSecondArgumentCompatible = o => true, })); // Is Object hash code calculcation well implemented? yield return(CreateHashCodeTest()); // Is strongly typed IEquatable equality method OK? Type[] equatableTypes = GetAllEquatableInterfaces(); foreach (Type type in equatableTypes) { var typeCopy = type; yield return(CreateEqualityTest(new EqualitySpecifications { Name = "EquatableEquals" + ((equatableTypes.Length == 1) ? String.Empty : "_" + typeCopy.Name), MethodFriendlyName = String.Format("bool Equals({0})", typeCopy.Name), ExpectedEquality = true, GetWorkingType = obj => GetEquatableInterface(obj, typeCopy), GetEqualityMethod = t => t.GetMethod("Equals", bindingAllInstance, null, new[] { typeCopy }, null), IsEqualityMethodRequired = o => typeCopy.IsAssignableFrom(o.GetType()), IsSecondArgumentCompatible = o => typeCopy.IsAssignableFrom(o.GetType()), })); } if (ImplementsOperatorOverloads) { // Is equality operator overload OK? yield return(CreateEqualityTest(new EqualitySpecifications { Name = "OperatorEquals", MethodFriendlyName = String.Format("static bool operator ==({0}, {0})", typeof(TTarget).Name), ExpectedEquality = true, GetWorkingType = o => o.GetType(), GetEqualityMethod = t => t.GetMethod("op_Equality", bindingAllStatic, null, new[] { typeof(TTarget), typeof(TTarget) }, null), IsEqualityMethodRequired = IsTargetTypeExactly, IsSecondArgumentCompatible = IsTargetTypeOrDerived, })); // Is inequality operator overload OK? yield return(CreateEqualityTest(new EqualitySpecifications { Name = "OperatorNotEquals", MethodFriendlyName = String.Format("static bool operator !=({0}, {0})", typeof(TTarget).Name), ExpectedEquality = false, GetWorkingType = o => o.GetType(), GetEqualityMethod = t => t.GetMethod("op_Inequality", bindingAllStatic, null, new[] { typeof(TTarget), typeof(TTarget) }, null), IsEqualityMethodRequired = IsTargetTypeExactly, IsSecondArgumentCompatible = IsTargetTypeOrDerived, })); } }
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Enum); args = new Type[] {}; method = type.GetMethod("GetTypeCode", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetTypeCode_0); args = new Type[] { typeof(System.Type) }; method = type.GetMethod("GetValues", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetValues_1); args = new Type[] { typeof(System.Type) }; method = type.GetMethod("GetNames", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetNames_2); args = new Type[] { typeof(System.Type), typeof(System.Object) }; method = type.GetMethod("GetName", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetName_3); args = new Type[] { typeof(System.Type), typeof(System.Object) }; method = type.GetMethod("IsDefined", flag, null, args, null); app.RegisterCLRMethodRedirection(method, IsDefined_4); args = new Type[] { typeof(System.Type) }; method = type.GetMethod("GetUnderlyingType", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetUnderlyingType_5); args = new Type[] { typeof(System.Type), typeof(System.String) }; method = type.GetMethod("Parse", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Parse_6); args = new Type[] { typeof(System.Type), typeof(System.String), typeof(System.Boolean) }; method = type.GetMethod("Parse", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Parse_7); args = new Type[] { typeof(System.Object) }; method = type.GetMethod("CompareTo", flag, null, args, null); app.RegisterCLRMethodRedirection(method, CompareTo_8); args = new Type[] {}; method = type.GetMethod("ToString", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToString_9); args = new Type[] { typeof(System.String) }; method = type.GetMethod("ToString", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToString_10); args = new Type[] { typeof(System.Type), typeof(System.Byte) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_11); args = new Type[] { typeof(System.Type), typeof(System.Int16) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_12); args = new Type[] { typeof(System.Type), typeof(System.Int32) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_13); args = new Type[] { typeof(System.Type), typeof(System.Int64) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_14); args = new Type[] { typeof(System.Type), typeof(System.Object) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_15); args = new Type[] { typeof(System.Type), typeof(System.SByte) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_16); args = new Type[] { typeof(System.Type), typeof(System.UInt16) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_17); args = new Type[] { typeof(System.Type), typeof(System.UInt32) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_18); args = new Type[] { typeof(System.Type), typeof(System.UInt64) }; method = type.GetMethod("ToObject", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToObject_19); args = new Type[] { typeof(System.Object) }; method = type.GetMethod("Equals", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Equals_20); args = new Type[] {}; method = type.GetMethod("GetHashCode", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetHashCode_21); args = new Type[] { typeof(System.Type), typeof(System.Object), typeof(System.String) }; method = type.GetMethod("Format", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Format_22); app.RegisterCLRCreateArrayInstance(type, s => new System.Enum[s]); }
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; FieldInfo field; Type[] args; Type type = typeof(FairyGUI.NTexture); args = new Type[] {}; method = type.GetMethod("get_Empty", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Empty_0); args = new Type[] {}; method = type.GetMethod("DisposeEmpty", flag, null, args, null); app.RegisterCLRMethodRedirection(method, DisposeEmpty_1); args = new Type[] {}; method = type.GetMethod("get_width", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_width_2); args = new Type[] {}; method = type.GetMethod("get_height", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_height_3); args = new Type[] {}; method = type.GetMethod("get_offset", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_offset_4); args = new Type[] {}; method = type.GetMethod("get_originalSize", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_originalSize_5); args = new Type[] { typeof(UnityEngine.Rect) }; method = type.GetMethod("GetDrawRect", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetDrawRect_6); args = new Type[] { typeof(UnityEngine.Vector2[]) }; method = type.GetMethod("GetUV", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetUV_7); args = new Type[] {}; method = type.GetMethod("get_root", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_root_8); args = new Type[] {}; method = type.GetMethod("get_disposed", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_disposed_9); args = new Type[] {}; method = type.GetMethod("get_nativeTexture", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_nativeTexture_10); args = new Type[] {}; method = type.GetMethod("get_alphaTexture", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_alphaTexture_11); args = new Type[] { typeof(System.String), typeof(System.String[]) }; method = type.GetMethod("GetMaterialManager", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetMaterialManager_12); args = new Type[] { typeof(FairyGUI.MaterialManager) }; method = type.GetMethod("DestroyMaterialManager", flag, null, args, null); app.RegisterCLRMethodRedirection(method, DestroyMaterialManager_13); args = new Type[] {}; method = type.GetMethod("Unload", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Unload_14); args = new Type[] { typeof(System.Boolean) }; method = type.GetMethod("Unload", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Unload_15); args = new Type[] { typeof(UnityEngine.Texture), typeof(UnityEngine.Texture) }; method = type.GetMethod("Reload", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Reload_16); args = new Type[] {}; method = type.GetMethod("Dispose", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Dispose_17); field = type.GetField("uvRect", flag); app.RegisterCLRFieldGetter(field, get_uvRect_0); app.RegisterCLRFieldSetter(field, set_uvRect_0); field = type.GetField("rotated", flag); app.RegisterCLRFieldGetter(field, get_rotated_1); app.RegisterCLRFieldSetter(field, set_rotated_1); field = type.GetField("refCount", flag); app.RegisterCLRFieldGetter(field, get_refCount_2); app.RegisterCLRFieldSetter(field, set_refCount_2); field = type.GetField("lastActive", flag); app.RegisterCLRFieldGetter(field, get_lastActive_3); app.RegisterCLRFieldSetter(field, set_lastActive_3); field = type.GetField("destroyMethod", flag); app.RegisterCLRFieldGetter(field, get_destroyMethod_4); app.RegisterCLRFieldSetter(field, set_destroyMethod_4); app.RegisterCLRCreateArrayInstance(type, s => new FairyGUI.NTexture[s]); args = new Type[] { typeof(UnityEngine.Texture) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); args = new Type[] { typeof(UnityEngine.Texture), typeof(UnityEngine.Texture), typeof(System.Single), typeof(System.Single) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_1); args = new Type[] { typeof(UnityEngine.Texture), typeof(UnityEngine.Rect) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_2); args = new Type[] { typeof(FairyGUI.NTexture), typeof(UnityEngine.Rect), typeof(System.Boolean) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_3); args = new Type[] { typeof(FairyGUI.NTexture), typeof(UnityEngine.Rect), typeof(System.Boolean), typeof(UnityEngine.Vector2), typeof(UnityEngine.Vector2) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_4); args = new Type[] { typeof(UnityEngine.Sprite) }; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_5); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultContractResolver"/> class. /// </summary> public DefaultContractResolver() { DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance; _typeContractCache = new ThreadSafeStore <Type, JsonContract>(CreateContract); }
public static ConstructorInfo GetConstructor(Type t) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; return(t.GetConstructors(bindingFlags).FirstOrDefault()); }
public void ConversionTest() { Single s = 2.5F; double d; Conversion conv; // primitives Assert.True(Conversion.TryGetConversion(typeof(Single), typeof(double), out conv)); Assert.False(conv.IsExplicit); object o = conv.Converter(s); d = (double)o; Console.WriteLine("{0}: {1}", o.GetType(), d); Assert.True(Conversion.TryGetConversion(typeof(double), typeof(Single), out conv)); Assert.True(conv.IsExplicit); o = conv.Converter(d); s = (Single)o; Console.WriteLine("{0}: {1}", o.GetType(), s); Assert.True(Conversion.TryGetConversion(typeof(object), typeof(double), out conv)); Assert.True(conv.IsExplicit); o = conv.Converter(s); d = (double)o; Console.WriteLine("{0}: {1}", o.GetType(), d); Assert.True(Conversion.TryGetConversion(typeof(double), typeof(int), out conv)); Assert.True(conv.IsExplicit); try { o = conv.Converter(d); Assert.True(false, "double to int conversion should not have succeeded."); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } // enums Assert.True(Conversion.TryGetConversion(typeof(string), typeof(BindingFlags), out conv)); Assert.True(conv.IsExplicit); BindingFlags flags = (BindingFlags)conv.Converter("Public"); // array up-conversion Assert.True(Conversion.TryGetConversion(typeof(double), typeof(double[]), out conv)); o = conv.Converter(d); double[] array = (double[])o; Console.WriteLine("{0}: {1}", o.GetType(), array[0]); Assert.True(Conversion.TryGetConversion(typeof(double[]), typeof(double[, ]), out conv)); o = conv.Converter(array); double[,] array2 = (double[, ])o; Console.WriteLine("{0}: {1}", o.GetType(), array2[0, 0]); Assert.True(Conversion.TryGetConversion(typeof(System.Reflection.Missing), typeof(double[]), out conv)); o = conv.Converter(d); array = (double[])o; Assert.Empty(array); Console.WriteLine("{0}: Length={1}", o.GetType(), array.Length); // class up-conversion Assert.True(Conversion.TryGetConversion(typeof(PositiveDefiniteMatrix), typeof(Matrix), out conv)); Assert.True(conv.Converter == null); // interface up-conversion Assert.True(Conversion.TryGetConversion(typeof(double[]), typeof(IList), out conv)); Assert.True(conv.Converter == null); // array covariance (C# 2.0 specification, sec 20.5.9) Assert.True(Conversion.TryGetConversion(typeof(string[]), typeof(IList <string>), out conv)); Assert.True(conv.Converter == null); Assert.True(Conversion.TryGetConversion(typeof(string[]), typeof(IList <object>), out conv)); Assert.True(conv.Converter == null); Assert.False(Conversion.TryGetConversion(typeof(string[, ]), typeof(IList <string>), out conv)); Assert.False(Conversion.TryGetConversion(typeof(string[, ]), typeof(IList <object>), out conv)); // array element conversion Assert.True(Conversion.TryGetConversion(typeof(object[]), typeof(double[]), out conv)); Assert.True(conv.IsExplicit); object[] oa = new object[2] { 1.1, 2.2 }; o = conv.Converter(oa); array = (double[])o; Assert.Equal(oa[0], array[0]); Assert.Equal(oa[1], array[1]); Console.WriteLine("{0}: {1} {2}", o.GetType(), array[0], array[1]); // array down-conversion Assert.True(Conversion.TryGetConversion(typeof(double[, ]), typeof(double[]), out conv)); array2 = new double[, ] { { 1.1, 2.2 } }; o = conv.Converter(array2); array = (double[])o; Console.WriteLine("{0}: {1} {2}", o.GetType(), array[0], array[1]); // custom conversion Assert.True(Conversion.TryGetConversion(typeof(Tester), typeof(int), out conv)); Tester t = new Tester(); o = conv.Converter(t); Console.WriteLine("{0}: {1}", o.GetType(), o); Assert.True(Conversion.TryGetConversion(typeof(Tester), typeof(int[]), out conv)); o = conv.Converter(t); Console.WriteLine("{0}: {1}", o.GetType(), o); // conversion from null Assert.False(Conversion.TryGetConversion(typeof(Nullable), typeof(int), out conv)); Assert.True(Conversion.TryGetConversion(typeof(Nullable), typeof(int?), out conv)); Assert.True(Conversion.TryGetConversion(typeof(Nullable), typeof(int[]), out conv)); }
/// <summary> /// Finds a collection of generic methods. /// </summary> /// <param name="type"></param> /// <param name="methodName">Is case insensitive</param> /// <param name="flags"></param> /// <param name="genericArgTypes"></param> /// <returns></returns> public static IEnumerable <MethodInfo> FindGenericMethods(Type type, string methodName, BindingFlags flags, Type[] genericArgTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { var methods = FindMethodsCore(t, methodName, flags); foreach (MethodInfo method in methods) { MethodInfo resolvedMethod; if (genericArgTypes != null && genericArgTypes.Length > 0) { var genericArgs = method.GetGenericArguments(); if (genericArgs.Length != genericArgTypes.Length) { continue; } // TODO: may need a try/catch around this call resolvedMethod = method.MakeGenericMethod(genericArgTypes); } else { resolvedMethod = method; } yield return(resolvedMethod); } } }
public static IEnumerable <KeyValuePair <MethodInfo, List <T> > > GetMethodsWithAttributes <T>(BindingFlags flags = kDefaultMethodBindingFlags) where T : Attribute { foreach (var m in GetAllTypes().SelectMany(t => t.GetMethods(flags))) { List <T> attribs = null; try { attribs = Attribute.GetCustomAttributes(m).Select(a => a as T).Where(a => a != null).ToList(); } catch (BadImageFormatException) { // ignore } if (attribs != null && attribs.Count > 0) { yield return(new KeyValuePair <MethodInfo, List <T> >(m, attribs)); } } }
/// <summary> /// Finds specific methods. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static IEnumerable <MethodInfo> FindMethods(Type type, string methodName, BindingFlags flags, Type[] parameterTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { var methods = FindMethodsCore(t, methodName, flags); foreach (MethodBase method in methods.Cast <MethodBase>()) { var parameters = method.GetParameters(); if (parameters.Length != parameterTypes.Length) { continue; } var candidateParameterTypes = parameters.Select(p => p.ParameterType); candidateParameterTypes = candidateParameterTypes.Select((cpt, i) => parameterTypes[i].GetTypeInfo().IsGenericTypeDefinition ? cpt.GetGenericTypeDefinition() : cpt); var ok = parameterTypes.Zip(candidateParameterTypes, (p, cp) => cp.IsAssignableFrom(p)).All(x => x); if (ok) { yield return((MethodInfo)method); } } } yield break; }
public static void Register(CSHotFix.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityEngine.ILogger); args = new Type[] {}; method = type.GetMethod("get_logHandler", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_logHandler_0); args = new Type[] { typeof(UnityEngine.ILogHandler) }; method = type.GetMethod("set_logHandler", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_logHandler_1); args = new Type[] {}; method = type.GetMethod("get_logEnabled", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_logEnabled_2); args = new Type[] { typeof(System.Boolean) }; method = type.GetMethod("set_logEnabled", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_logEnabled_3); args = new Type[] {}; method = type.GetMethod("get_filterLogType", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_filterLogType_4); args = new Type[] { typeof(UnityEngine.LogType) }; method = type.GetMethod("set_filterLogType", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_filterLogType_5); args = new Type[] { typeof(UnityEngine.LogType) }; method = type.GetMethod("IsLogTypeAllowed", flag, null, args, null); app.RegisterCLRMethodRedirection(method, IsLogTypeAllowed_6); args = new Type[] { typeof(UnityEngine.LogType), typeof(System.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_7); args = new Type[] { typeof(UnityEngine.LogType), typeof(System.Object), typeof(UnityEngine.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_8); args = new Type[] { typeof(UnityEngine.LogType), typeof(System.String), typeof(System.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_9); args = new Type[] { typeof(UnityEngine.LogType), typeof(System.String), typeof(System.Object), typeof(UnityEngine.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_10); args = new Type[] { typeof(System.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_11); args = new Type[] { typeof(System.String), typeof(System.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_12); args = new Type[] { typeof(System.String), typeof(System.Object), typeof(UnityEngine.Object) }; method = type.GetMethod("Log", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Log_13); args = new Type[] { typeof(System.String), typeof(System.Object) }; method = type.GetMethod("LogWarning", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogWarning_14); args = new Type[] { typeof(System.String), typeof(System.Object), typeof(UnityEngine.Object) }; method = type.GetMethod("LogWarning", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogWarning_15); args = new Type[] { typeof(System.String), typeof(System.Object) }; method = type.GetMethod("LogError", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogError_16); args = new Type[] { typeof(System.String), typeof(System.Object), typeof(UnityEngine.Object) }; method = type.GetMethod("LogError", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogError_17); args = new Type[] { typeof(UnityEngine.LogType), typeof(System.String), typeof(System.Object[]) }; method = type.GetMethod("LogFormat", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogFormat_18); args = new Type[] { typeof(System.Exception) }; method = type.GetMethod("LogException", flag, null, args, null); app.RegisterCLRMethodRedirection(method, LogException_19); app.RegisterCLRCreateArrayInstance(type, s => new UnityEngine.ILogger[s]); }
/// <summary> /// 获取某个属性的值 /// </summary> /// <param name="container">数据源</param> /// <param name="propName">属性名</param> /// <param name="exist">是否存在此属性</param> /// <returns>属性值</returns> internal static object GetPropertyValue(object container, string propName, out bool exist) { exist = false; object value = null; if (container == null) { throw new ArgumentNullException("container"); } if (string.IsNullOrEmpty(propName)) { throw new ArgumentNullException("propName"); } if (Utility.IsInteger(propName)) { #region 索引值部分 //属性名只为数字.则取数组索引 int index = Utility.ConverToInt32(propName); if (container is IList) { IList iList = (IList)container; if (iList.Count > index) { exist = true; value = iList[index]; } } else if (container is ICollection) { ICollection ic = (ICollection)container; if (ic.Count > index) { exist = true; IEnumerator ie = ic.GetEnumerator(); int i = 0; while (i++ <= index) { ie.MoveNext(); } value = ie.Current; } } else { //判断是否含有索引属性 PropertyInfo item = container.GetType().GetProperty("Item", new Type[] { typeof(int) }); if (item != null) { try { value = item.GetValue(container, new object[] { index }); exist = true; } catch { exist = false; } } } #endregion } else { #region 字段/属性/键值 //容器是类型.则查找静态属性或字段 Type type = container is Type ? (Type)container : container.GetType(); BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase; if (!(container is Type)) { flags |= BindingFlags.Instance; } //查找字段 FieldInfo field = type.GetField(propName, flags); if (field != null) { exist = true; value = field.GetValue(container); } else { //查找属性 PropertyInfo property = type.GetProperty(propName, flags, null, null, Type.EmptyTypes, new ParameterModifier[0]); if (property != null) { exist = true; value = property.GetValue(container, null); } else if (container is ICustomTypeDescriptor) { //已实现ICustomTypeDescriptor接口 ICustomTypeDescriptor ictd = (ICustomTypeDescriptor)container; PropertyDescriptor descriptor = ictd.GetProperties().Find(propName, true); if (descriptor != null) { exist = true; value = descriptor.GetValue(container); } } else if (container is IDictionary) { //是IDictionary集合 IDictionary idic = (IDictionary)container; if (idic.Contains(propName)) { exist = true; value = idic[propName]; } } else if (container is NameObjectCollectionBase) { //是NameObjectCollectionBase派生对象 NameObjectCollectionBase nob = (NameObjectCollectionBase)container; //调用私有方法 MethodInfo method = nob.GetType().GetMethod("BaseGet", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string) }, new ParameterModifier[] { new ParameterModifier(1) }); if (method != null) { value = method.Invoke(container, new object[] { propName }); exist = value != null; } } else { //判断是否含有索引属性 PropertyInfo item = type.GetProperty("Item", new Type[] { typeof(string) }); if (item != null) { try { value = item.GetValue(container, new object[] { propName }); exist = true; } catch { exist = false; } } } } #endregion } return(value); }
/// <summary> /// Finds a specific method. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static MethodInfo FindMethod(Type type, string methodName, BindingFlags flags, Type[] parameterTypes) { return(FindMethods(type, methodName, flags, parameterTypes).FirstOrDefault()); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return(baseType.GetFields(bindingAttr)); }
/// <summary> /// Finds all the methods that match specific criteria. /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="flags"></param> /// <param name="genericArgTypes"></param> /// <param name="parameterTypes"></param> /// <returns></returns> public static IEnumerable <MethodInfo> FindMethods(Type type, string methodName, BindingFlags flags, Type[] genericArgTypes, Type[] parameterTypes) { foreach (Type t in GetSelfAndBaseTypes(type)) { var methods = FindMethodsCore(t, methodName, flags); foreach (MethodInfo method in methods) { MethodInfo resolvedMethod; if (genericArgTypes != null && genericArgTypes.Length > 0) { var genericArgs = method.GetGenericArguments(); if (genericArgs.Length != genericArgTypes.Length) { continue; } // TODO: may need a try/catch around this call resolvedMethod = method.MakeGenericMethod(genericArgTypes); } else { resolvedMethod = method; } var parameters = resolvedMethod.GetParameters(); if (parameters.Length != parameterTypes.Length) { continue; } var candidateParameterTypes = parameters.Select(p => p.ParameterType); var ok = parameterTypes.Zip(candidateParameterTypes, (p, cp) => cp.IsAssignableFrom(p)).All(x => x); if (ok) { yield return(resolvedMethod); } } } }
public override FieldInfo GetField(string name, BindingFlags bindingAttr) { return(baseType.GetField(name, bindingAttr)); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return(baseType.GetMembers(bindingAttr)); }