【问题标题】:Why 'typeof(string).FullName' is giving 'System.String' and not 'string'?为什么'typeof(string).FullName'给出'System.String'而不是'string'?
【发布时间】:2015-12-09 10:31:45
【问题描述】:

为什么typeof(string).FullNameSystem.String 而不是string?所有其他“简单”类型也是如此,例如intfloatdouble、...

我知道typeof 正在返回给定类型的System.Type 对象,但为什么string 不是System.Type 对象?

是不是因为string是c#语言的一部分,而System.Type是系统库的一部分?

【问题讨论】:

  • 这是因为stringSystem.String 类的别名,该类位于System 命名空间中。如果你使用typeof(string).Name,你只会得到类名String
  • 除了上面 Tim Schmelter 的评论:对于原语也可以这样说:typeof(int).FullName 将返回 int,但 typeof(Int32).FullName 将返回 @ 987654341@。 System.Stringstring 完全相同,根据喜好使用。我个人将string 用于字段,将String 用于静态方法/常量,例如String.EmptyString.Format(...)。我一直认为它们在所有方面都完全相同,但显然它们的 type-FullName 也不同。所以感谢这个问题,因为现在我也学到了一些新东西。 :)

标签: c# types typeof


【解决方案1】:

因为stringSystem.String 的别名。您的string C# 代码在编译时转换为System.Stringother aliases 也是如此。

【讨论】:

  • 那么它们之间的速度没有区别?我认为 System.Type 更“复杂”?
  • 不。 stringSystem.String 的全部 100%。
【解决方案2】:

在 C# 中,string 只是 System.String 的别名,所以两者相同,typeof 返回相同的类型对象。

所有其他原始类型也是如此。例如,int 只是 System.Int32 的别名。

如果需要获取某个类型的较短的 C# 别名,可以使用CSharpCodeProvider.GetTypeOutput() 代替FullName

using Microsoft.CSharp;

[...]

var compiler = new CSharpCodeProvider();
var type = new CodeTypeReference(typeof(Int32));
Console.WriteLine(compiler.GetTypeOutput(type)); // Prints int

(代码 sn-p 取自this question

【讨论】:

  • 感谢您的提示,但创建一个 CSharpCodeProvider 是否不会为此“昂贵”,特别是如果您经常这样做?
  • 我没有测量它,但如果你需要经常这样做,我建议将 c# 名称缓存在 Dictionary<Type,string> 或类似的东西中。如果您需要这个名字,请在字典中查找。如果不在里面,执行慢速GetTypeOutput,保存到字典中。
  • 10.000 次尝试花了我 11 毫秒。所以性能不是问题。
猜你喜欢
  • 2017-02-21
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 2010-10-04
  • 2010-10-26
  • 2023-04-08
  • 2019-07-20
  • 2018-11-24
相关资源
最近更新 更多