Getting correct method signature

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrus

    Getting correct method signature


    How to get syntactically correct signature which compiles for code template
    grneration ?
    I tried code below but it creates syntactically incorrect signature.

    Andrus.

    using System;
    using System.Collecti ons.Generic;

    public class MainClass
    {
    static string GetSignature(Ty pe xTheType, string method)
    {
    var xModule = xTheType.Module ;
    var xTheMethod = xTheType.GetMet hod(method);
    return xTheMethod.ToSt ring();
    }

    public static void Main()
    {
    // Observed: Void Test(System.Obj ect,
    System.Collecti ons.Generic.Lis t`1[System.String])
    // Expected: public void Test(object p1, List<stringp2)
    // or some other syntactically correct signature
    Console.WriteLi ne(GetSignature (typeof(MainCla ss), "Test"));
    }

    public void Test(object p1, List<stringp2)
    {
    }
    }

  • Jeff Johnson

    #2
    Re: Getting correct method signature

    "Andrus" <kobruleht2@hot .eewrote in message
    news:ug0vqH0OJH A.2348@TK2MSFTN GP05.phx.gbl...
    // Observed: Void Test(System.Obj ect,
    System.Collecti ons.Generic.Lis t`1[System.String])
    The `x in the type name tells you how many parameters the generic takes, and
    the parameters (if that's the right word) are then listed afterwords in
    brackets, comma delimited, I believe. (Check it on a Dictionary.) So you'd
    just need to do a little parsing and substringing to rewrite the type in a
    C#-friendly manner.


    Comment

    • Andrus

      #3
      Re: Getting correct method signature

      Jeff,
      > // Observed: Void Test(System.Obj ect,
      >System.Collect ions.Generic.Li st`1[System.String])
      >
      The `x in the type name tells you how many parameters the generic takes,
      and the parameters (if that's the right word) are then listed afterwords
      in brackets, comma delimited, I believe. (Check it on a Dictionary.) So
      you'd just need to do a little parsing and substringing to rewrite the
      type in a C#-friendly manner.
      Thank you.
      Where to find some sample code for this?
      How to get method parameter names also as defined in method code?
      Why it outputs Void with upper case ?

      andrus.

      Comment

      • Jeff Johnson

        #4
        Re: Getting correct method signature

        "Andrus" <kobruleht2@hot .eewrote in message
        news:eNv4I33OJH A.4780@TK2MSFTN GP02.phx.gbl...
        >> // Observed: Void Test(System.Obj ect,
        >>System.Collec tions.Generic.L ist`1[System.String])
        >>
        >The `x in the type name tells you how many parameters the generic takes,
        >and the parameters (if that's the right word) are then listed afterwords
        >in brackets, comma delimited, I believe. (Check it on a Dictionary.) So
        >you'd just need to do a little parsing and substringing to rewrite the
        >type in a C#-friendly manner.
        Where to find some sample code for this?
        Sample code for what? Manipulating strings? I'm sure you can do something
        that simple....
        How to get method parameter names also as defined in method code?
        Hmm, I don't deal with this kind of Reflection very often. Let me take a
        look.

        Okay, from a cursory glance at MSDN, calling MethodInfo.GetP arameters() gets
        you an array of ParameterInfo objects. These objects have a Name property.
        Does that work for you?
        Why it outputs Void with upper case ?
        I'm willing to bet that that's the Frameworks "neutral" version of the
        keyword, just like you're getting a type of System.Object instead of the
        C#-specific "object" keyword.

        I just noticed you're using the "var" keyword. I don't use the 3.x Framework
        (I'm basing my responses on 2.0) so I don't know if anything's changed. I
        doubt it, since my MSDN is current.


        Comment

        • Andrus

          #5
          Re: Getting correct method signature

          Jeff,
          Sample code for what? Manipulating strings? I'm sure you can do something
          that simple....
          Sample code for C# method signature disassembler.

          Andrus.

          Comment

          • Jeff Johnson

            #6
            Re: Getting correct method signature

            "Andrus" <kobruleht2@hot .eewrote in message
            news:%236bkqW4O JHA.4144@TK2MSF TNGP02.phx.gbl. ..
            >Sample code for what? Manipulating strings? I'm sure you can do something
            >that simple....
            >
            Sample code for C# method signature disassembler.
            Well, you're kind of in luck today. I dabbled in writing my own object
            browser a while back, and I still have the code. It's in VB, and this was
            pre-generics, so you're not going to get exactly what you want (note the
            TODO near the end) but it should be a start.

            Private Function GetSignature(By Val method As MethodInfo) As String
            Dim firstParam As Boolean = True
            ' TODO: Don't hardcode the function open/close characters
            Dim sigBuilder As StringBuilder = New StringBuilder(m ethod.Name & "(")
            Dim displayType As String

            For Each param As ParameterInfo In method.GetParam eters()
            If param.Parameter Type.FullName IsNot Nothing Then
            Dim paramType As String = param.Parameter Type.FullName

            If paramType.EndsW ith("&") Then
            paramType = paramType.Subst ring(0, paramType.Lengt h - 1)
            End If

            Select Case paramType.ToLow er()
            Case "system.obj ect"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "object"
            Else
            displayType = "Object"
            End If
            Case "system.str ing"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "string"
            Else
            displayType = "String"
            End If
            Case "system.int 32"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "int"
            Else
            displayType = "Integer"
            End If
            Case "system.int 16"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "short"
            Else
            displayType = "Short"
            End If
            Case "system.byt e"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "byte"
            Else
            displayType = "Byte"
            End If
            Case "system.int 64"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "long"
            Else
            displayType = "Long"
            End If
            Case "system.boolean "
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "bool"
            Else
            displayType = "Boolean"
            End If
            Case "system.cha r"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "char"
            Else
            displayType = "Char"
            End If
            Case "system.datetim e"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = paramType ' No equivalent in C#
            Else
            displayType = "Date"
            End If
            Case "system.dou ble"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "double"
            Else
            displayType = "Double"
            End If
            Case "system.sin gle"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "float"
            Else
            displayType = "Single"
            End If
            Case "system.sby te"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "sbyte"
            Else
            displayType = "SByte"
            End If
            Case "system.uin t32"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "uint"
            Else
            displayType = "UInteger"
            End If
            Case "system.uin t16"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "ushort"
            Else
            displayType = "UShort"
            End If
            Case "system.uin t64"
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "ulong"
            Else
            displayType = "ULong"
            End If
            Case "system.decimal "
            If m_viewStyle = ViewStyle.CShar p Then
            displayType = "decimal"
            Else
            displayType = paramType ' No equivalent in VB
            End If
            Case Else
            displayType = paramType
            End Select

            If firstParam Then
            firstParam = False
            Else
            sigBuilder.Appe nd(", ")
            End If

            If m_viewStyle = ViewStyle.CShar p Then
            If param.Parameter Type.IsByRef Then
            sigBuilder.Appe nd("ref ")
            ElseIf param.IsOut Then
            sigBuilder.Appe nd("out ")
            End If
            Else
            If param.Parameter Type.IsByRef Then
            sigBuilder.Appe nd("ByRef ")
            End If
            End If

            sigBuilder.Appe nd(displayType)
            Else
            ' TODO: Handle generics
            Return String.Empty
            End If
            Next

            sigBuilder.Appe nd(")")

            Return sigBuilder.ToSt ring()
            End Function


            Comment

            • Andrus

              #7
              Re: Getting correct method signature

              Well, you're kind of in luck today. I dabbled in writing my own object
              browser a while back, and I still have the code. It's in VB, and this was
              pre-generics, so you're not going to get exactly what you want (note the
              TODO near the end) but it should be a start.
              Thank you. Using this I created code below.
              If I pass method name containing generic type parameters to GetMSignature
              GetMethod returns null.

              How to change this that it works for generic method also: builds signature
              with generic type parameters and their constraints ?

              Andrus.


              static string GetMSignature(T ype xTheType, string method)
              {
              var xModule = xTheType.Module ;
              MethodInfo xTheMethod = xTheType.GetMet hod(method);
              xTheMethod = xTheType.GetMet hod(method);
              return GetSignature(xT heMethod);
              }


              static string GetSignature(Me thodInfo method)
              {
              bool firstParam = true;
              StringBuilder sigBuilder = new
              StringBuilder(R eflectionUtil.T ypeName(method. ReturnType));
              sigBuilder.Appe nd(' ');
              sigBuilder.Appe nd(method.Name + "(");
              foreach (ParameterInfo param in method.GetParam eters())
              {
              if (firstParam)
              firstParam = false;
              else
              sigBuilder.Appe nd(", ");

              if (param.Paramete rType.IsByRef)
              sigBuilder.Appe nd("ref ");
              else if (param.IsOut)
              sigBuilder.Appe nd("out ");
              sigBuilder.Appe nd(TypeName(par am.ParameterTyp e));
              sigBuilder.Appe nd(' ');
              sigBuilder.Appe nd(param.Name);
              }
              sigBuilder.Appe nd(")");
              return sigBuilder.ToSt ring();
              }

              /// <summary>
              /// Get full type name with full namespace names
              /// </summary>
              /// <param name="type">Typ e. May be generic or nullable</param>
              /// <returns>Full type name, fully qualified namespaces</returns>
              public static string TypeName(Type type)
              {
              Type nullableType = Nullable.GetUnd erlyingType(typ e);
              if (nullableType != null)
              return nullableType.Na me + "?";

              if (!type.IsGeneri cType)
              switch (type.Name)
              {
              case "String": return "string";
              case "Int32": return "int";
              case "Decimal": return "decimal";
              case "Object": return "object";
              case "Void": return "void";
              default: return type.FullName;
              }

              StringBuilder sb = new StringBuilder(t ype.Name.Substr ing(0,
              type.Name.Index Of('`'))
              );
              sb.Append('<');
              bool first = true;
              foreach (Type t in type.GetGeneric Arguments())
              {
              if (!first)
              {
              sb.Append(',');
              first = false;
              }
              sb.Append(TypeN ame(t));
              }
              sb.Append('>');
              return sb.ToString();
              }

              Comment

              • Jeff Johnson

                #8
                Re: Getting correct method signature

                "Andrus" <kobruleht2@hot .eewrote in message
                news:%235WdeO5O JHA.4424@TK2MSF TNGP02.phx.gbl. ..
                >Well, you're kind of in luck today. I dabbled in writing my own object
                >browser a while back, and I still have the code. It's in VB, and this was
                >pre-generics, so you're not going to get exactly what you want (note the
                >TODO near the end) but it should be a start.
                >
                Thank you. Using this I created code below.
                If I pass method name containing generic type parameters to GetMSignature
                GetMethod returns null.
                >
                How to change this that it works for generic method also: builds signature
                with generic type parameters and their constraints ?
                I'm afraid that's up to you. The MethodInfo class has methods and properties
                like GetGenericArgum ents() and IsGeneric method. As you can see, I never
                implemented them, nor did I even look into them.


                Comment

                Working...