【问题标题】:How to get simplified ReturnType through MethodInfo? [duplicate]如何通过 MethodInfo 获得简化的 ReturnType? [复制]
【发布时间】:2020-08-10 23:05:04
【问题描述】:

使用反射来获取 MethodInfo,我想获取一个更用户友好的 ReturnType 版本,用于一些自文档。

目前这个 methodInfo.ReturnType.Name 返回类似 Dictionary2 or IEnumerable1 的内容。

虽然这个methodInfo.ReturnType.FullName; 返回一个太长的版本,比如System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral]]

System.Collections.Generic.IEnumerable`1[[ProjectName.Namespace.Item, ProjectName, Version=1.9.0.0, Culture=neutral, PublicKeyToken=null]]

理论上我可以做一些字符串操作来摆脱所有显示的多余信息,但如果可能的话我想避免这种情况。

【问题讨论】:

  • 这能回答你的问题吗? C# Get Generic Type Name 。在那里查看投票最多的答案
  • 是的,这个答案正是我想要的!谢谢。

标签: c# reflection code-documentation methodinfo


【解决方案1】:

通过一些字符串操作,您可以轻松地递归地自己构建好名字:

private static string NiceName(Type t)
{
    var indexOfH = t.Name.IndexOf('`');
    return (indexOfH >= 0 ? t.Name.Substring(0, indexOfH) : t.Name) + (t.IsGenericType ? $"<{string.Join(",", t.GenericTypeArguments.Select(NiceName))}>" : "");
}

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 2013-04-20
    • 2013-04-05
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多