public GetGenericArguments ( ) : System.Type[] | ||
return | System.Type[] |
protected virtual string FormatMethod(MethodBase method) { var sb = new StringBuilder(); if (method.DeclaringType != null) { sb.Append(method.DeclaringType.FullName); sb.Append("."); } sb.Append(method.Name); if (method.IsGenericMethod) { sb.Append("<"); sb.Append(string.Join(", ", method.GetGenericArguments().Select(t => t.Name))); sb.Append(">"); } sb.Append("("); var f = false; foreach (var p in method.GetParameters()) { if (f) sb.Append(", "); else f = true; sb.Append(p.ParameterType.Name); sb.Append(' '); sb.Append(p.Name); } sb.Append(")"); return sb.ToString(); }
public ReflectionMethod(MethodBase methodBase, ReflectionClass declaringType) : base(declaringType, methodBase is ConstructorInfo ? "#ctor" : methodBase.Name) { if (methodBase is MethodInfo) { this.ReturnType = ReflectionReturnType.Create(this, ((MethodInfo)methodBase).ReturnType, false); } else if (methodBase is ConstructorInfo) { this.ReturnType = DeclaringType.DefaultReturnType; } foreach (ParameterInfo paramInfo in methodBase.GetParameters()) { this.Parameters.Add(new ReflectionParameter(paramInfo, this)); } if (methodBase.IsGenericMethodDefinition) { foreach (Type g in methodBase.GetGenericArguments()) { this.TypeParameters.Add(new DefaultTypeParameter(this, g)); } int i = 0; foreach (Type g in methodBase.GetGenericArguments()) { declaringType.AddConstraintsFromType(this.TypeParameters[i++], g); } } if (methodBase.IsStatic) { foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(methodBase)) { string attributeName = data.Constructor.DeclaringType.FullName; if (attributeName == "System.Runtime.CompilerServices.ExtensionAttribute" || attributeName == "Boo.Lang.ExtensionAttribute") { this.IsExtensionMethod = true; } } } ModifierEnum modifiers = ModifierEnum.None; if (methodBase.IsStatic) { modifiers |= ModifierEnum.Static; } if (methodBase.IsPrivate) { // I assume that private is used most and public last (at least should be) modifiers |= ModifierEnum.Private; } else if (methodBase.IsFamily || methodBase.IsFamilyOrAssembly) { modifiers |= ModifierEnum.Protected; } else if (methodBase.IsPublic) { modifiers |= ModifierEnum.Public; } else { modifiers |= ModifierEnum.Internal; } if (methodBase.IsVirtual) { modifiers |= ModifierEnum.Virtual; } if (methodBase.IsAbstract) { modifiers |= ModifierEnum.Abstract; } this.Modifiers = modifiers; }
public ReflectionMethod(MethodBase methodBase, ReflectionClass declaringType) : base(declaringType, methodBase is ConstructorInfo ? "#ctor" : methodBase.Name) { if (methodBase is MethodInfo) { MethodInfo m = ((MethodInfo)methodBase); this.ReturnType = ReflectionReturnType.Create(this, m.ReturnType, attributeProvider: m.ReturnTypeCustomAttributes); } else if (methodBase is ConstructorInfo) { this.ReturnType = DeclaringType.DefaultReturnType; } foreach (ParameterInfo paramInfo in methodBase.GetParameters()) { this.Parameters.Add(new ReflectionParameter(paramInfo, this)); } if (methodBase.IsGenericMethodDefinition) { foreach (Type g in methodBase.GetGenericArguments()) { this.TypeParameters.Add(new DefaultTypeParameter(this, g)); } int i = 0; foreach (Type g in methodBase.GetGenericArguments()) { ReflectionClass.AddConstraintsFromType(this.TypeParameters[i++], g); } } ModifierEnum modifiers = ModifierEnum.None; if (methodBase.IsStatic) { modifiers |= ModifierEnum.Static; } if (methodBase.IsPrivate) { // I assume that private is used most and public last (at least should be) modifiers |= ModifierEnum.Private; } else if (methodBase.IsFamily || methodBase.IsFamilyOrAssembly) { modifiers |= ModifierEnum.Protected; } else if (methodBase.IsPublic) { modifiers |= ModifierEnum.Public; } else { modifiers |= ModifierEnum.Internal; } if (methodBase.IsFinal) { modifiers |= ModifierEnum.Sealed; } else if (methodBase.IsAbstract) { modifiers |= ModifierEnum.Abstract; } else if (methodBase.IsVirtual) { if ((methodBase.Attributes & MethodAttributes.NewSlot) != 0) modifiers |= ModifierEnum.Virtual; else modifiers |= ModifierEnum.Override; } this.Modifiers = modifiers; ReflectionClass.AddAttributes(declaringType.ProjectContent, this.Attributes, CustomAttributeData.GetCustomAttributes(methodBase)); ApplySpecialsFromAttributes(this); }
public ModuleScopeTokenResolver(MethodBase method) { m_enclosingMethod = method; m_module = method.Module; m_methodContext = (method is ConstructorInfo) ? null : method.GetGenericArguments(); m_typeContext = (method.DeclaringType == null) ? null : method.DeclaringType.GetGenericArguments(); }
public static string GetId(MethodBase methodOrConstructor) { var genericPart = string.Empty; if (methodOrConstructor.IsGenericMethod) { genericPart = string.Format(CultureInfo.InvariantCulture, "``{0}", methodOrConstructor.GetGenericArguments().Length); } var parametersPart = string.Join( ",", methodOrConstructor.GetParameters() .Select(x => GetTypeName(x.ParameterType))); if (!string.IsNullOrEmpty(parametersPart)) { parametersPart = "(" + parametersPart + ")"; } var conversionReturnTypePart = string.Empty; if (methodOrConstructor.IsSpecialName && (methodOrConstructor.Name.Equals("op_Explicit") || methodOrConstructor.Name.Equals("op_Implicit"))) { conversionReturnTypePart = "~" + GetTypeName(((MethodInfo)methodOrConstructor).ReturnType); } return string.Format( CultureInfo.InvariantCulture, "M:{0}.{1}{2}{3}{4}", GetTypeName(methodOrConstructor.ReflectedType), HashEncode(methodOrConstructor.Name), genericPart, parametersPart, conversionReturnTypePart); }
public bool MethodSigEquals(MethodBaseSig sig, MethodBase method) { if (sig == null || method == null) return false; if (sig.HasThis != !method.IsStatic) return false; if (sig.Generic != method.IsGenericMethod) return false; if (sig.Generic) { if (sig.GenParamCount != method.GetGenericArguments().Length) return false; } if (method.IsMethodSpec()) method = method.Module.ResolveMethod(method.MetadataToken) ?? method; var mps = method.GetParameters(); if (sig.Params.Count != mps.Length) return false; var minfo = method as MethodInfo; if (minfo != null) { if (!Equals(sig.RetType, minfo.ReturnType)) return false; } else { if (sig.RetType.RemovePinnedAndModifiers().GetElementType() != ElementType.Void) return false; } for (int i = 0; i < mps.Length; i++) { if (!Equals(sig.Params[i], mps[i].ParameterType)) return false; } return true; }
MethodBodyReader (MethodBase method) { this.method = method; this.body = method.GetMethodBody (); if (this.body == null) throw new ArgumentException ("Method has no body"); var bytes = body.GetILAsByteArray (); if (bytes == null) throw new ArgumentException ("Can not get the body of the method"); if (!(method is ConstructorInfo)) method_arguments = method.GetGenericArguments (); if (method.DeclaringType != null) type_arguments = method.DeclaringType.GetGenericArguments (); if (!method.IsStatic) this_parameter = new ThisParameter(method.DeclaringType); this.parameters = method.GetParameters (); this.locals = body.LocalVariables; this.module = method.Module; this.il = new ByteBuffer (bytes); this.instructions = new List<Instruction> ((bytes.Length + 1) / 2); }
private void AppendMethod(StringBuilder builder, MethodBase method) { if (method.DeclaringType != null) { AppendType(builder, method.DeclaringType); builder.Append("."); } AppendName(builder, method.Name); if (method.IsGenericMethod) { builder.Append("["); method.GetGenericArguments().ForEach((type, index) => { if (index > 0) builder.Append(","); AppendType(builder, type); }); builder.Append("]"); } builder.Append("("); method.GetParameters().ForEach((parameter, index) => { if (index > 0) builder.Append(", "); builder.Append(parameter.ParameterType.Name) .Append(" ") .Append(parameter.Name); }); builder.Append(")"); }
MethodReference ImportMethodSpecification(SR.MethodBase method, ImportGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) { throw new InvalidOperationException(); } var element_method = ImportMethod(method_info.GetGenericMethodDefinition(), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod(element_method); var arguments = method.GetGenericArguments(); var instance_arguments = instance.GenericArguments; context.Push(element_method); try { for (int i = 0; i < arguments.Length; i++) { instance_arguments.Add(ImportType(arguments [i], context)); } return(instance); } finally { context.Pop(); } }
public static Type[] GetGenericArguments(MethodBase methodBase) { try { return methodBase.GetGenericArguments(); } catch (NotSupportedException) { return new Type[0]; } }
public MethodBaseModuleContext(MethodBase method) { this.module = method.Module; this.methodGenericArguments = (method.IsGenericMethod || method.IsGenericMethodDefinition) ? method.GetGenericArguments() : new Type[0]; var type = method.DeclaringType; this.typeGenericArguments = (type != null && (type.IsGenericType || type.IsGenericTypeDefinition)) ? type.GetGenericArguments() : new Type[0]; }
static public string Declaration(this MethodBase method) { if (method.IsGenericMethod) { return(string.Concat(method.Name, "<", string.Join(", ", method.GetGenericArguments().Select(__Type.Declaration)), ">(", string.Join(", ", method.GetParameters().Select(__ParameterInfo.Declaration)), ")")); } return(string.Concat(method.Name, "(", string.Join(", ", method.GetParameters().Select(__ParameterInfo.Declaration)), ")")); }
public MethodReference ImportMethod(SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification(method) || ImportOpenGenericMethod(method, import_kind)) { return(ImportMethodSpecification(method, context)); } var declaring_type = ImportType(method.DeclaringType, context); if (IsGenericInstance(method.DeclaringType)) { method = method.Module.ResolveMethod(method.MetadataToken); } var reference = new MethodReference(method.Name, module.Import(typeof(void))) { Name = method.Name, HasThis = HasCallingConvention(method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention(method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType(method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention(method, SR.CallingConventions.VarArgs)) { reference.CallingConvention &= MethodCallingConvention.VarArg; } if (method.IsGenericMethod) { ImportGenericParameters(reference, method.GetGenericArguments()); } context.Push(reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType(method_info.ReturnType, context) : ImportType(typeof(void), default(ImportGenericContext)); var parameters = method.GetParameters(); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) { reference_parameters.Add( new ParameterDefinition(ImportType(parameters[i].ParameterType, context))); } reference.DeclaringType = declaring_type; return(reference); } finally { context.Pop(); } }
public TokenResolver(ITypeLoader typeLoader, MethodBase method) { this.typeLoader = typeLoader; this.module = method.Module; var type = method.DeclaringType; if(type != null) this.typeArguments = type.GetGenericArguments(); if(!(method.IsConstructor || method.IsSpecialName) && method.IsGenericMethod) this.methodArguments = method.GetGenericArguments(); }
string GetName(bcl.MethodBase method) { if (method.IsGenericMethod) { var genericArgs = method.GetGenericArguments(); return(method.Name + "<" + string.Join(", ", genericArgs.Select(TypeUtils.ToFriendlyName)) + ">"); } return(method.Name); }
/// <summary> /// Gets the formatting strings representing a method. /// </summary> /// <param name="method">A <see cref="MethodBase"/>.</param> /// <returns></returns> public static MethodFormatStrings GetMethodFormatStrings(MethodBase method) { string typeFormat; bool typeIsGeneric; string methodFormat; bool methodIsGeneric; string parameterFormat; StringBuilder stringBuilder = new StringBuilder(); typeFormat = GettypeFormatString(method.DeclaringType); typeIsGeneric = method.DeclaringType.IsGenericTypeDefinition; // Build the format string for the method name. stringBuilder.Length = 0; stringBuilder.Append("::"); stringBuilder.Append(method.Name); if (method.IsGenericMethodDefinition) { methodIsGeneric = true; stringBuilder.Append("<"); for (int i = 0; i < method.GetGenericArguments().Length; i++) { if (i > 0) stringBuilder.Append(", "); stringBuilder.AppendFormat("{{{0}}}", i); } stringBuilder.Append(">"); } else { methodIsGeneric = false; } methodFormat = stringBuilder.ToString(); // Build the format string for parameters. stringBuilder.Length = 0; ParameterInfo[] parameters = method.GetParameters(); stringBuilder.Append("("); for (int i = 0; i < parameters.Length; i++) { if (i > 0) { stringBuilder.Append(", "); } stringBuilder.Append("{{{"); stringBuilder.Append(i); stringBuilder.Append("}}}"); } stringBuilder.Append(")"); parameterFormat = stringBuilder.ToString(); return new MethodFormatStrings(typeFormat, typeIsGeneric, methodFormat, methodIsGeneric, parameterFormat); }
/// <summary> Creates a MethodReference from System.Reflections MethodInfo or ConstructorInfo. Also works for property getters, setters, static constructors, ... </summary> public static MethodReference FromReflection(R.MethodBase method) { Assert.False(method.IsGenericMethodDefinition); var signature = MethodSignature.FromReflection(method); var declaringType = ((TypeReference.SpecializedTypeCase)TypeReference.FromType(method.DeclaringType)).Item; var methodArgs = method.IsGenericMethod ? method.GetGenericArguments().EagerSelect(TypeReference.FromType) : ImmutableArray <TypeReference> .Empty; return(new MethodReference(signature, declaringType.TypeArguments, methodArgs)); }
public String Format( Object instance, MethodBase method, Object[] invocationParameters) { String[] parts = { Formatter.FormatString(_typeFormat, method.DeclaringType.GetGenericArguments()), Formatter.FormatString(_methodFormat, method.GetGenericArguments()), instance == null ? "" : String.Format("{{{0}}}", instance ), Formatter.FormatString(_parameterFormat, invocationParameters) }; return String.Concat(parts); }
public static StringBuilder FormatSignature(StringBuilder result, MethodBase method, Func<Type, string> nameDispenser) { ContractUtils.RequiresNotNull(result, "result"); ContractUtils.RequiresNotNull(method, "method"); ContractUtils.RequiresNotNull(nameDispenser, "nameDispenser"); MethodInfo methodInfo = method as MethodInfo; if (methodInfo != null) { FormatTypeName(result, methodInfo.ReturnType, nameDispenser); result.Append(' '); } MethodBuilder builder = method as MethodBuilder; if (builder != null) { result.Append(builder.Signature); return result; } ConstructorBuilder cb = method as ConstructorBuilder; if (cb != null) { result.Append(cb.Signature); return result; } FormatTypeName(result, method.DeclaringType, nameDispenser); result.Append("::"); result.Append(method.Name); if (!method.IsConstructor) { FormatTypeArgs(result, method.GetGenericArguments(), nameDispenser); } result.Append("("); if (!method.ContainsGenericParameters) { ParameterInfo[] ps = method.GetParameters(); for (int i = 0; i < ps.Length; i++) { if (i > 0) result.Append(", "); FormatTypeName(result, ps[i].ParameterType, nameDispenser); if (!System.String.IsNullOrEmpty(ps[i].Name)) { result.Append(" "); result.Append(ps[i].Name); } } } else { result.Append("?"); } result.Append(")"); return result; }
static StackObject *GetGenericArguments_14(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.MethodBase instance_of_this_method = (System.Reflection.MethodBase) typeof(System.Reflection.MethodBase).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetGenericArguments(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
protected static string GenerateMethodName(MethodBase method) { var stringBuilder = new StringBuilder(); stringBuilder.Append(method.Name); bool first = true; if (method is MethodInfo && method.IsGenericMethod) { Type[] genericArguments = method.GetGenericArguments(); stringBuilder.Append("["); for (int i = 0; i < genericArguments.Length; i++) { if (!first) { stringBuilder.Append(","); } else { first = false; } stringBuilder.Append(genericArguments[i].Name); } stringBuilder.Append("]"); } stringBuilder.Append("("); ParameterInfo[] parameters = method.GetParameters(); first = true; for (int i = 0; i < parameters.Length; ++i) { if (!first) { stringBuilder.Append(", "); } else { first = false; } string type = "<UnknownType>"; if (parameters[i].ParameterType != null) { type = parameters[i].ParameterType.Name; } stringBuilder.Append(type + " " + parameters[i].Name); } stringBuilder.Append(")"); return stringBuilder.ToString(); }
public static MethodIdentifier Method(MethodBase method, Type type) { string name = method.Name; var parameters = new List<TypeIdentifier>(); if (method.IsGenericMethod) name += GenericMethodParamaterPrefix + method.GetGenericArguments().Length; foreach (ParameterInfo param in method.GetParameters()) { parameters.Add(ParameterType(method, param.ParameterType)); } return new MethodIdentifier(name, parameters.ToArray(), method.IsStatic, method.IsPublic, method.IsConstructor, Type(type)); }
/// <summary> /// Gets a string representing a concrete method invocation. /// </summary> /// <param name="instance">Instance on which the method is invoked.</param> /// <param name="method">Invoked method.</param> /// <param name="invocationParameters">Concrete invocation parameters.</param> /// <returns>A representation of the method invocation.</returns> public string Format( object instance, MethodBase method, object[] invocationParameters) { string[] parts = new string[4] { typeIsGeneric ? Formatter.FormatString(this.typeFormat, method.DeclaringType.GetGenericArguments()) : this.typeFormat, methodIsGeneric ? Formatter.FormatString(this.methodFormat, method.GetGenericArguments()) : this.methodFormat, instance == null ? "" : string.Format("{{{0}}}", instance), Formatter.FormatString(this.parameterFormat, invocationParameters) }; return string.Concat(parts); }
public static MethodSignature FromReflection(R.MethodBase method) { method = SanitizeDeclaringTypeGenerics(method.IsGenericMethod ? ((R.MethodInfo)method).GetGenericMethodDefinition() : method); var declaringType = TypeSignature.FromType(method.DeclaringType); var accessibility = method.IsPublic ? Accessibility.APublic : method.IsAssembly ? Accessibility.AInternal : method.IsPrivate ? Accessibility.APrivate : method.IsFamily ? Accessibility.AProtected : method.IsFamilyOrAssembly ? Accessibility.AProtectedInternal : method.IsFamilyAndAssembly ? Accessibility.APrivateProtected : throw new NotSupportedException("Unsupported accessibility of " + method); var parameters = method.GetParameters().EagerSelect(p => { var t = TypeReference.FromType(p.ParameterType); return(new MethodParameter(t, p.Name ?? "", p.HasDefaultValue, p.HasDefaultValue ? CanonicalizeDefaultValue(p.DefaultValue, t) : null, p.IsDefined(typeof(ParamArrayAttribute), true))); }); var genericParameters = method.IsGenericMethodDefinition ? method.GetGenericArguments() : method.IsGenericMethod ? ((R.MethodInfo)method).GetGenericMethodDefinition().GetGenericArguments() : Type.EmptyTypes; var returnType = method is R.MethodInfo mi ? TypeReference.FromType(mi.ReturnType) : TypeSignature.Void; var isDestructor = method.Name == "Finalize" && !method.IsStatic && method is R.MethodInfo min && min.ReturnType == typeof(void) && min.GetParameters().Length == 0; return(new MethodSignature(declaringType, parameters, method.Name, returnType, method.IsStatic, accessibility, method.IsVirtual && !method.IsFinal && declaringType.CanOverride, isOverride: (method as R.MethodInfo)?.GetBaseDefinition() != method, method.IsAbstract, method.IsSpecialName || isDestructor, genericParameters.EagerSelect(GenericParameter.FromType) )); }
private string GenerateMethodName(MethodBase method) { var stringBuilder = new StringBuilder(); stringBuilder.Append(method.Name); if (method is MethodInfo && method.IsGenericMethod) { Type[] genericArguments = method.GetGenericArguments(); stringBuilder.Append("["); int index2 = 0; bool flag2 = true; for (; index2 < genericArguments.Length; ++index2) { if (!flag2) stringBuilder.Append(","); else flag2 = false; stringBuilder.Append(genericArguments[index2].Name); } stringBuilder.Append("]"); } stringBuilder.Append("("); ParameterInfo[] parameters = method.GetParameters(); bool flag3 = true; for (int index2 = 0; index2 < parameters.Length; ++index2) { if (!flag3) stringBuilder.Append(", "); else flag3 = false; string str2 = "<UnknownType>"; if (parameters[index2].ParameterType != null) str2 = parameters[index2].ParameterType.Name; stringBuilder.Append(str2 + " " + parameters[index2].Name); } stringBuilder.Append(")"); return stringBuilder.ToString(); }
private MethodBodyReader(MethodBase method) { _method = method; _body = method.GetMethodBody(); if (_body == null) throw new ArgumentException("Method has no body"); var iLAsByteArray = _body.GetILAsByteArray(); if (iLAsByteArray == null) throw new ArgumentException("Can not get the body of the method"); if (!(method is ConstructorInfo)) _methodArguments = method.GetGenericArguments(); if (method.DeclaringType != null) _typeArguments = method.DeclaringType.GetGenericArguments(); _parameters = method.GetParameters(); _locals = _body.LocalVariables; _module = method.Module; _il = new ByteBuffer(iLAsByteArray); }
/// <summary> /// Defines the generic method parameters based on the specified method. /// </summary> /// <param name="methodBuilder">The method builder.</param> /// <param name="methodBase">The method base.</param> /// <returns>The generic parameter types.</returns> /// <remarks> /// Custom attributes are not considered by this method. /// </remarks> public static Type[] DefineGenericParameters(this MethodBuilder methodBuilder, MethodBase methodBase) { if (methodBuilder == null) throw new ArgumentNullException("methodBuilder"); if (methodBase == null) throw new ArgumentNullException("methodBase"); if (!methodBase.IsGenericMethodDefinition) return Type.EmptyTypes; var genericParameterTypes = methodBase.GetGenericArguments(); var genericParameterNames = Array.ConvertAll(genericParameterTypes, t => t.Name); var genericParameterBuilders = methodBuilder.DefineGenericParameters(genericParameterNames); foreach (var genericParameterBuilder in genericParameterBuilders) { var genericParameterType = genericParameterTypes[genericParameterBuilder.GenericParameterPosition]; // Set generic parameter attributes. genericParameterBuilder.SetGenericParameterAttributes(genericParameterType.GenericParameterAttributes); // Set generic parameter constraints. var genericParameterConstraints = genericParameterType.GetGenericParameterConstraints(); var baseTypeConstraint = genericParameterConstraints.FirstOrDefault(t => t.IsClass); if (baseTypeConstraint != null) genericParameterBuilder.SetBaseTypeConstraint(baseTypeConstraint); var interfaceConstraints = genericParameterConstraints.Where(t => t.IsInterface).ToArray(); genericParameterBuilder.SetInterfaceConstraints(interfaceConstraints); } return Array.ConvertAll(genericParameterBuilders, b => (Type) b); }
MethodReference ImportMethodSpecification(SR.MethodBase method, IGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) { throw new InvalidOperationException(); } var element_method = ImportMethod(method_info.GetGenericMethodDefinition(), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod(element_method); var arguments = method.GetGenericArguments(); var instance_arguments = instance.GenericArguments; for (int i = 0; i < arguments.Length; i++) { TypeReference toAdd = ImportType(arguments[i], context ?? element_method); instance_arguments.Add(toAdd); /*Telerik authorship*/ instance.AddGenericArgument(toAdd); } return(instance); }
private static string BuildMethodGenericParametersUnescaped(MethodBase method) { Debug.Assert(method.IsGenericMethod); return "<" + string.Join(", ", method.GetGenericArguments().Select(PrettyPrintTypeName)) + ">"; }
private MethodBodyReader(MethodBase method, MethodBody mb) { this.method = method; body = mb; if (body == null) throw new ArgumentException(); var bytes = body.GetILAsByteArray(); if (bytes == null) throw new ArgumentException(); if (!(method is ConstructorInfo)) method_arguments = method.GetGenericArguments(); if (method.DeclaringType != null) generic_type_arguments = method.DeclaringType.GetGenericArguments(); parameters = method.GetParameters(); locals = body.LocalVariables; module = method.Module; il = new ByteBuffer(bytes); }
private static bool tryMakeGenericMethod(ref MethodBase method) { var genericArguments = method.GetGenericArguments(); var constraintedArgumentTypes = new Type[genericArguments.Length]; for (var i = 0; i < genericArguments.Length; i++) { var argumentType = genericArguments[i]; var parameterConstraints = argumentType.GetGenericParameterConstraints(); if (parameterConstraints.Length == 0 || !parameterConstraints[0].IsClass) return false; constraintedArgumentTypes[i] = parameterConstraints[0]; } method = ((MethodInfo)method).MakeGenericMethod(constraintedArgumentTypes); return true; }
public static TypeIdentifier ParameterType(MethodBase method, Type type) { if (type.IsArray) { var elementType = type.GetElementType(); if (elementType.IsGenericParameter) { return method.IsGenericMethod && method.GetGenericArguments().Any(t => t.TypeHandle.Value == elementType.TypeHandle.Value) ? new TypeIdentifier(GenericMethodParamaterPrefix + elementType.GenericParameterPosition + ArrayTypeSuffix, GenericTypeNamespace) : new TypeIdentifier(GenericTypeParameterPrefix + elementType.GenericParameterPosition + ArrayTypeSuffix, GenericTypeNamespace); } } if (type.IsGenericParameter) { return method.IsGenericMethod && method.GetGenericArguments().Any(t => t.TypeHandle.Value == type.TypeHandle.Value) ? new TypeIdentifier(GenericMethodParamaterPrefix + type.GenericParameterPosition, GenericTypeNamespace) : new TypeIdentifier(GenericTypeParameterPrefix + type.GenericParameterPosition, GenericTypeNamespace); } return new TypeIdentifier(type.Name, type.Namespace); }
public static string GetSignature(this MethodBase method, bool includeAccessModifiers = false, bool includeReturn = false, bool includeDeclaringType = true, bool useFullNames = false, bool includeParameters = true, bool includeParametersNames = false, Func <bool, bool, MethodBase, object, string> parametersFunction = null, object parametersFunctionArguments = null ) { StringBuilder res = new StringBuilder(); // Access modifiers if (includeAccessModifiers) { if (method.IsPublic) { res.Append("public "); } else if (method.IsPrivate) { res.Append("private "); } else if (method.IsAssembly) { res.Append("internal "); } if (method.IsFamily) { res.Append("protected "); } if (method.IsStatic) { res.Append("static "); } if (method.IsVirtual) { res.Append("virtual "); } if (method.IsAbstract) { res.Append("abstract "); } } // Return type if (includeReturn) { if (method is MethodInfo mi) { res.Append(mi.ReturnType.GetSignature(useFullNames) + " "); } else { res.Append("<ctor> "); } } // Method name if (includeDeclaringType) { res.Append(method.DeclaringType.GetSignature(useFullNames) + "."); } res.Append(method.Name); // Generics arguments if (method.IsGenericMethod) { res.Append("<"); Type[] genericArgs = method.GetGenericArguments(); for (int i = 0; i < genericArgs.Length; i++) { res.Append((i > 0 ? ", " : "") + genericArgs[i].GetSignature(useFullNames)); } res.Append(">"); } // Parameters if (includeParameters) { res.Append("("); if (parametersFunction != null) { res.Append(parametersFunction(useFullNames, includeParametersNames, method, parametersFunctionArguments)); } else { ParameterInfo[] pars = method.GetParameters(); for (int i = 0; i < pars.Length; i++) { ParameterInfo par = pars[i]; if (i == 0 && method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false)) { res.Append("this "); } if (par.ParameterType.IsByRef) { res.Append("ref "); } else if (par.IsOut) { res.Append("out "); } res.Append(par.ParameterType.GetSignature(useFullNames)); if (includeParametersNames) { res.Append(" " + par.Name); } if (i < pars.Length - 1) { res.Append(", "); } } } res.Append(")"); } return(res.ToString()); }
/// <summary> /// Returns a method signature display string. Used to display stack frames. /// </summary> /// <returns>Null if the method is a compiler generated method that shouldn't be displayed to the user.</returns> internal virtual string FormatMethodSignature(MethodBase method) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; var declaringType = method.DeclaringType; var options = new CommonTypeNameFormatterOptions(arrayBoundRadix: NumberRadixDecimal, showNamespaces: true); builder.Append(TypeNameFormatter.FormatTypeName(declaringType, options)); builder.Append('.'); builder.Append(method.Name); builder.Append(TypeNameFormatter.FormatTypeArguments(method.GetGenericArguments(), options)); builder.Append('('); bool first = true; foreach (var parameter in method.GetParameters()) { if (first) { first = false; } else { builder.Append(", "); } builder.Append(FormatRefKind(parameter)); builder.Append(TypeNameFormatter.FormatTypeName(parameter.ParameterType, options)); } builder.Append(')'); return pooled.ToStringAndFree(); }
private static string GetMethodName(MethodBase mInfo) { string ret; if (mInfo.IsGenericMethod) { ret = string.Format("{0}{1}{2}", GetExplicitName(mInfo.Name), // mInfo.Name.Replace('.', '#'), "``" + mInfo.GetGenericArguments().Length.ToString(), CreateParameterSignature( mInfo, mInfo.GetParameters().Select(p => p.ParameterType).ToArray())); } else { ret = string.Format("{0}{1}", GetExplicitName(mInfo.Name), // mInfo.Name.Replace('.', '#'), CreateParameterSignature( mInfo, mInfo.GetParameters().Select(p => p.ParameterType).ToArray())); } return ret; }
static private IEnumerable <Instruction> Body(this MethodBase method, byte[] buffer) { if (buffer == null) { yield break; } var _authority = new Authority(method); var _stream = new MemoryStream(buffer); var _reader = new BinaryReader(_stream); var _code = OpCodes.Nop; while (_stream.Position < _stream.Length) { var _byte = _reader.ReadByte(); if (_byte != 0xFE) { _code = __MethodBase.m_Single[_byte]; } else { _byte = _reader.ReadByte(); _code = __MethodBase.m_Double[_byte]; } switch (_code.OperandType) { case OperandType.InlineNone: yield return(new Instruction(_code, null, null)); break; case OperandType.ShortInlineBrTarget: yield return(new Instruction <Label>(_code, _reader.ReadShortLabel())); break; case OperandType.InlineBrTarget: yield return(new Instruction <Label>(_code, _reader.ReadLabel())); break; case OperandType.ShortInlineI: yield return(new Instruction <byte>(_code, _reader.ReadByte())); break; case OperandType.InlineI: yield return(new Instruction <int>(_code, _reader.ReadInt32())); break; case OperandType.InlineI8: yield return(new Instruction <long>(_code, _reader.ReadInt64())); break; case OperandType.ShortInlineR: yield return(new Instruction <float>(_code, _reader.ReadSingle())); break; case OperandType.InlineR: yield return(new Instruction <double>(_code, _reader.ReadDouble())); break; case OperandType.ShortInlineVar: yield return(new Instruction <byte>(_code, _reader.ReadByte())); break; case OperandType.InlineVar: yield return(new Instruction <short>(_code, _reader.ReadInt16())); break; case OperandType.InlineString: yield return(new Instruction <string>(_code, _authority.String(_reader.ReadInt32()))); break; case OperandType.InlineSig: yield return(new Instruction <byte[]>(_code, _authority.Signature(_reader.ReadInt32()))); break; case OperandType.InlineField: yield return(new Instruction <FieldInfo>(_code, _authority.Field(_reader.ReadInt32(), method.DeclaringType == null ? new Type[0] : method.DeclaringType.GetGenericArguments(), method.IsGenericMethod ? method.GetGenericArguments() : new Type[0]))); break; case OperandType.InlineMethod: var _method = _authority.Method(_reader.ReadInt32(), method.DeclaringType == null ? new Type[0] : method.DeclaringType.GetGenericArguments(), method.IsGenericMethod ? method.GetGenericArguments() : new Type[0]); if (_method is ConstructorInfo) { yield return(new Instruction <ConstructorInfo>(_code, (ConstructorInfo)_method)); } else { yield return(new Instruction <MethodInfo>(_code, (MethodInfo)_method)); } break; case OperandType.InlineType: yield return(new Instruction <Type>(_code, _authority.Type(_reader.ReadInt32(), method.DeclaringType == null ? new Type[0] : method.DeclaringType.GetGenericArguments(), method.IsGenericMethod ? method.GetGenericArguments() : new Type[0]))); break; case OperandType.InlineTok: var _member = (MemberInfo)_authority.Member(_reader.ReadInt32(), method.DeclaringType == null ? new Type[0] : method.DeclaringType.GetGenericArguments(), method.IsGenericMethod ? method.GetGenericArguments() : new Type[0]); if (_member is FieldInfo) { yield return(new Instruction <FieldInfo>(_code, (FieldInfo)_member)); } else if (_member is ConstructorInfo) { yield return(new Instruction <ConstructorInfo>(_code, (ConstructorInfo)_member)); } else if (_member is MethodInfo) { yield return(new Instruction <MethodInfo>(_code, (MethodInfo)_member)); } else if (_member is Type) { yield return(new Instruction <Type>(_code, (Type)_member)); } break; case OperandType.InlineSwitch: yield return(new Instruction <Label[]>(OpCodes.Switch, Enumerable.Range(0, Convert.ToInt32(_reader.ReadUInt32())).Select(_Iterator => _reader.ReadLabel()).ToArray())); break; default: throw new NotSupportedException(); } } }
public static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi) { var declaringType = mi.DeclaringType; if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition) declaringType = declaringType.GetGenericTypeDefinition (); // Get generic definition const BindingFlags bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; foreach (var m in declaringType.GetMethods (bindingflags)) { if (m.MetadataToken == mi.MetadataToken) { mi = m; break; } } sb.Append (declaringType.ToString ()); sb.Append ("."); sb.Append (mi.Name); if (mi.IsGenericMethod) { Type[] gen_params = mi.GetGenericArguments (); sb.Append ("["); for (int j = 0; j < gen_params.Length; j++) { if (j > 0) sb.Append (","); sb.Append (gen_params [j].Name); } sb.Append ("]"); } ParameterInfo[] p = mi.GetParameters (); sb.Append (" ("); for (int i = 0; i < p.Length; ++i) { if (i > 0) sb.Append (", "); Type pt = p[i].ParameterType; if (pt.IsGenericType && ! pt.IsGenericTypeDefinition) pt = pt.GetGenericTypeDefinition (); sb.Append (pt.ToString()); if (p [i].Name != null) { sb.Append (" "); sb.Append (p [i].Name); } } sb.Append (")"); }
internal void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi) { ParameterInfo[] p = mi.GetParametersInternal (); sb.Append (mi.DeclaringType.ToString ()); sb.Append ("."); sb.Append (mi.Name); if (mi.IsGenericMethod) { Type[] gen_params = mi.GetGenericArguments (); sb.Append ("["); for (int j = 0; j < gen_params.Length; j++) { if (j > 0) sb.Append (","); sb.Append (gen_params [j].Name); } sb.Append ("]"); } sb.Append (" ("); for (int i = 0; i < p.Length; ++i) { if (i > 0) sb.Append (", "); Type pt = p[i].ParameterType; if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) { sb.Append (pt.Namespace); sb.Append ("."); } sb.Append (pt.Name); if (p [i].Name != null) { sb.Append (" "); sb.Append (p [i].Name); } } sb.Append (")"); }
[System.Security.SecurityCritical] // auto-generated private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes) { Type[] parameterTypes; Type returnType; int tkParent; int cGenericParameters = 0; if (method.IsGenericMethod) { if (!method.IsGenericMethodDefinition) throw new InvalidOperationException(); cGenericParameters = method.GetGenericArguments().Length; } if (optionalParameterTypes != null) { if ((method.CallingConvention & CallingConventions.VarArgs) == 0) { // Client should not supply optional parameter in default calling convention throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention")); } } MethodInfo masmi = method as MethodInfo; if (method.DeclaringType.IsGenericType) { MethodBase methDef = null; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S> MethodOnTypeBuilderInstantiation motbi; ConstructorOnTypeBuilderInstantiation cotbi; if ((motbi = method as MethodOnTypeBuilderInstantiation) != null) { methDef = motbi.m_method; } else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null) { methDef = cotbi.m_ctor; } else if (method is MethodBuilder || method is ConstructorBuilder) { // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S> methDef = method; } else { Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); if (method.IsGenericMethod) { Contract.Assert(masmi != null); methDef = masmi.GetGenericMethodDefinition(); methDef = methDef.Module.ResolveMethod( method.MetadataToken, methDef.DeclaringType != null ? methDef.DeclaringType.GetGenericArguments() : null, methDef.GetGenericArguments()); } else { methDef = method.Module.ResolveMethod( method.MetadataToken, method.DeclaringType != null ? method.DeclaringType.GetGenericArguments() : null, null); } } parameterTypes = methDef.GetParameterTypes(); returnType = MethodBuilder.GetMethodBaseReturnType(methDef); } else { parameterTypes = method.GetParameterTypes(); returnType = MethodBuilder.GetMethodBaseReturnType(method); } int sigLength; byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes, optionalParameterTypes, cGenericParameters).InternalGetSignature(out sigLength); if (method.DeclaringType.IsGenericType) { int length; byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length); tkParent = GetTokenFromTypeSpec(sig, length); } else if (!method.Module.Equals(this)) { // Use typeRef as parent because the method's declaringType lives in a different assembly tkParent = GetTypeToken(method.DeclaringType).Token; } else { // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments if (masmi != null) tkParent = GetMethodToken(masmi).Token; else tkParent = GetConstructorToken(method as ConstructorInfo).Token; } return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength); }
/// <summary> /// /// </summary> /// <param name="method"></param> /// <returns></returns> public static string GetMemberID(MethodBase method) { string memberName; memberName = "M:" + GetFullNamespaceName(method) + "." + method.Name.Replace('.', '#').Replace('+', '#'); #if NET_2_0 if (method.HasGenericArguments) memberName = memberName + "``" + method.GetGenericArguments().Length; #endif memberName += GetParameterList(method); if (method is MethodInfo) { MethodInfo mi = (MethodInfo)method; if (mi.Name == "op_Implicit" || mi.Name == "op_Explicit") { memberName += "~" + mi.ReturnType; } } return memberName; }
private static int _ReadOperand(MethodBase This, OpCode code, int position, byte[] il, Module module, ILInstruction instruction) { int metadataToken; switch (code.OperandType) { case OperandType.InlineBrTarget: { metadataToken = ReadInt32(il, ref position); metadataToken += position; instruction.Operand = metadataToken; break; } case OperandType.InlineField: { metadataToken = ReadInt32(il, ref position); instruction.Operand = module.ResolveField(metadataToken); break; } case OperandType.InlineMethod: { metadataToken = ReadInt32(il, ref position); try { instruction.Operand = module.ResolveMethod(metadataToken); } catch { instruction.Operand = module.ResolveMember(metadataToken); } break; } case OperandType.InlineSig: { metadataToken = ReadInt32(il, ref position); instruction.Operand = module.ResolveSignature(metadataToken); break; } case OperandType.InlineTok: { metadataToken = ReadInt32(il, ref position); try { instruction.Operand = module.ResolveType(metadataToken); } catch { } // SSS : see what to do here break; } case OperandType.InlineType: { metadataToken = ReadInt32(il, ref position); // now we call the ResolveType always using the generic attributes type in order // to support decompilation of generic methods and classes // thanks to the guys from code project who commented on this missing feature instruction.Operand = module.ResolveType(metadataToken, This.DeclaringType.GetGenericArguments(), This.GetGenericArguments()); break; } case OperandType.InlineI: { instruction.Operand = ReadInt32(il, ref position); break; } case OperandType.InlineI8: { instruction.Operand = ReadInt64(il, ref position); break; } case OperandType.InlineNone: { instruction.Operand = null; break; } case OperandType.InlineR: { instruction.Operand = ReadDouble(il, ref position); break; } case OperandType.InlineString: { metadataToken = ReadInt32(il, ref position); instruction.Operand = module.ResolveString(metadataToken); break; } case OperandType.InlineSwitch: { var count = ReadInt32(il, ref position); var casesAddresses = new int[count]; for (var i = 0; i < count; i++) { casesAddresses[i] = ReadInt32(il, ref position); } var cases = new int[count]; for (var i = 0; i < count; i++) { cases[i] = position + casesAddresses[i]; } break; } case OperandType.InlineVar: { instruction.Operand = ReadUInt16(il, ref position); break; } case OperandType.ShortInlineBrTarget: { instruction.Operand = ReadSByte(il, ref position) + position; break; } case OperandType.ShortInlineI: { if (instruction.Code == OpCodes.Ldc_I4_S) { instruction.Operand = ReadSByte(il, ref position); } else { instruction.Operand = ReadByte(il, ref position); } break; } case OperandType.ShortInlineR: { instruction.Operand = ReadSingle(il, ref position); break; } case OperandType.ShortInlineVar: { instruction.Operand = ReadByte(il, ref position); break; } default: { throw new Exception("Unknown operand type."); } } return(position); }