【问题标题】:How to get string representation of a built-in type alias [duplicate]如何获取内置类型别名的字符串表示形式
【发布时间】:2020-03-26 10:44:35
【问题描述】:

如果我使用typeof(int).Name,我会得到“Int32”。 有没有办法直接从系统中获取“int”,而无需我对“Int32”进行任何字符串操作?

【问题讨论】:

  • 您能添加一个从Type 映射到string 的字典并用它查找吗?
  • 查看this answer and its comments 中的讨论。获得编写类型名称的“C# 原生方式”并不是特别有用。你为什么要这样做?
  • int 是一个 C# 主义,运行时中没有任何东西知道他的语言特定名称(也不应该有,尽管它很流行,但 C# 不是仅 .NET 语言)。您可以为 C# 具有专用名称的所有类型编写一个简单的查找表;这是一个固定的清单。可以想象,你也可以依赖 Roslyn(不知何故),但这似乎有点矫枉过正。
  • 这能回答你的问题吗? Is there a way to get a type's alias through reflection? 完全相同的副本
  • @PavelAnikhouski 啊是的,这实际上是完全相同的情况,但在建议中没有看到它。我会将其标记为重复。谢谢。 :)

标签: c#


【解决方案1】:

我为此使用字典。很可能是几年前从另一个 StackOverflow 答案中得到的,但目前找不到...

private static readonly Dictionary<Type, string> Aliases =
    new Dictionary<Type, string>()
{
    { typeof(byte), "byte" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(ushort), "ushort" },
    { typeof(int), "int" },
    { typeof(uint), "uint" },
    { typeof(long), "long" },
    { typeof(ulong), "ulong" },
    { typeof(float), "float" },
    { typeof(double), "double" },
    { typeof(decimal), "decimal" },
    { typeof(object), "object" },
    { typeof(bool), "bool" },
    { typeof(char), "char" },
    { typeof(string), "string" },
    { typeof(void), "void" }
};

【讨论】:

  • string result = Aliases.TryGetValue(typeOfInterest, out string value) ? value : typeOfInterest.Name;
  • 我猜是这个answer,看起来完全一样
猜你喜欢
  • 2020-01-14
  • 2011-08-27
  • 1970-01-01
  • 2017-06-13
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
相关资源
最近更新 更多