获取不包括标准的类型



我有这样的方法:

public async Task<IEnumerable<DataResponse>> GetAsync() { ... }

我使用反射,并且我想要得到类型";数据响应";,但我得到类型";任务<IEnumerable>quot;

static void Main(string[] args)
{
var assemblies = GetAssemblies();
IEnumerable<Type> controllers =
assemblies.SelectMany(a => a.GetTypes().Where(t => t.IsSubclassOf(typeof(ControllerBase))));
foreach (var controller in controllers)
{
var methods = controller.GetMethods();
foreach (var methodInfo in methods)
{
var returnType = methodInfo.ReturnType;
}
}
}

如何获得排除标准类型("task"、"IEnumerable"、e.t.c(的类型?

任务<IEnumerable>是一个泛型类型,其一个泛型参数IEnumerable又是一个其泛型参数为DataResponse 的泛型类型

因此methodInfo.ReturnType.GetGenericTypeArguments(([0]。GetGenericTypeArguments(。

当然,这并不能解决所有案件。

一种更通用的方法

// Pass all types you want to strip here, for example, List<>, IList<>, Task<>, etc.
returnType = StripTypes(returnType, typeof(Task<>), typeof(IEnumerable<>), typeof(List<>));
static Type StripTypes(Type type, params Type[] typesToStrip)
{
if (!type.IsGenericType)
{
return type;
}
var definition = type.GetGenericTypeDefinition();
if (Array.IndexOf(typesToStrip, definition) >= 0)
{
return StripTypes(type.GetGenericArguments()[0], typesToStrip);
}
return type;
}

最新更新