3

I'm porting an open source library from the regular .NET 4 Client Profile to DNX Core 5.0. There are quite a few library changes, with properties or methods being moved around or altogether removed. I have looked at this answer but it doesn't work in my case because the method was removed.

One of the issue I have a piece of code where MethodBase.GetCurrentMethod() is called. This method no longer exists in the API. The only methods left that are similar are:

public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle);
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType);

But I'm not sure what the 'handle' is. I need to get the MethodBase in order to access its parameters to then process them for a REST API query. This is the code that builds the object in .NET 4:

public static Annotation Annotation(string query = null, string text = null, string type = null, string name = null, string entity = null, int limit = 25, int offset = 0)
    {
      var search = Help.SearchToString(MethodBase.GetCurrentMethod(), query, text, type, name, entity);
      return Help.Find<Annotation>(search, limit, offset, "annotation");
    }

And it is then used here:

public static string SearchToString(MethodBase m, params object[] search)
    {
      var paras = m.GetParameters();
      var result = string.Empty;

      for (var i = 0; i < search.Length; i++)
      {
        if (search[i] != null)
        {
          if (i == 0)
          {
            result += search[i] + "%20AND%20";
          }
          else
          {
            result += paras[i].Name.ToLower() + ":" + search[i] + "%20AND%20";
          }         
        }      
      }

      return result.LastIndexOf("%20AND%20", StringComparison.Ordinal) > 0
        ? result.Substring(0, result.LastIndexOf("%20AND%20", StringComparison.Ordinal))
        : result;
    }

What other way could I have to access the MethodBase object parameters in SearchToString() method if I can't easily pass the said MethodBase as a parameter?

Community
  • 1
  • 1
Astaar
  • 5,858
  • 8
  • 40
  • 57
  • Hi @Astaar, have you found a solution? I have the same problem with a .net core application, can't do this anymore: MethodBase.GetCurrentMethod(); – Thomas May 10 '16 at 20:12

1 Answers1

3

Assuming the method Annotation is in the class TestClass, use

typeof(TestClass).GetMethod(nameof(Annotation))
Sidoine
  • 310
  • 3
  • 9
  • this doesn't work exactly the same way and produces an exception when mutiple methods share the same name. – Jack Mar 01 '17 at 06:35