这段代码错了吗?它只是没有返回任何东西:
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;
}
它返回一个空的枚举器。
注意:我在ASP.NET MVC控制器上调用它来寻找ActionResults
GetMethodsOfReturnType(typeof(ProductsController), typeof(ActionResult));
答案 0 :(得分:11)
其他人已指出修正案,但我想建议IsSubclassOf
的替代方案以及公共方法:
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;
}
使用IsAssignableFrom
,您不需要额外的“返回类型与所需类型完全相同”测试,并且它也适用于接口。
答案 1 :(得分:1)
BindingFlags.NonPublic | BindingFlags.Instance
Where(m => ret == m.ReturnType || m.ReturnType.IsSubclassOf(ret))
答案 2 :(得分:1)
可能使这项工作发生的两项变化:
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;
}