Get all methods with the given return type

Is this code incorrect? It just returns nothing:

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   var methods = cls.GetMethods(BindingFlags.NonPublic);
   var retMethods = methods.Where(m => m.ReturnType.IsSubclassOf(ret))
                           .Select(m => m.Name);
   return retMethods;
}

It returns an empty counter.

Note. I call it on an ASP.NET MVC controller that is looking for ActionResults

GetMethodsOfReturnType(typeof(ProductsController), typeof(ActionResult));
+3
source share
3 answers

Others indicated corrections, but I would like to suggest an alternative IsSubclassOf, and also include public methods:

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   // Did you really mean to prohibit public methods? I assume not
   var methods = cls.GetMethods(BindingFlags.NonPublic | 
                                BindingFlags.Public |
                                BindingFlags.Instance);
   var retMethods = methods.Where(m => m.ReturnType.IsAssignableFrom(ret))
                           .Select(m => m.Name);
   return retMethods;
}

With IsAssignableFromyou, you don’t need to have an additional “return type exactly the same as the required type”, and it will also work with interfaces.

+11
source
BindingFlags.NonPublic | BindingFlags.Instance

Where(m => ret == m.ReturnType || m.ReturnType.IsSubclassOf(ret))
+1
source

, :

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   var methods = cls.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
   var retMethods = methods.Where(m => m.ReturnType.IsSubclassOf(ret) || m.ReturnType == ret)
                           .Select(m => m.Name);
   return retMethods;
}
+1

Source: https://habr.com/ru/post/1742325/


All Articles