MyEnum.Item.ToString()和nameof(MyEnum.Item)有什么区别? [英] What is the difference between MyEnum.Item.ToString() and nameof(MyEnum.Item)?

查看:60
本文介绍了MyEnum.Item.ToString()和nameof(MyEnum.Item)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  MyEnum.Item.ToString();nameof(MyEnum.Item); 

首选哪种样式?两者之间有什么实际区别吗?

解决方案

第一个是运行时调用,它将在运行时意识到需要返回字符串"Item" ,然后执行此操作

第二种方法是将"Item" 直接写入代码中的另一种方法.

第二个会稍快一些,但是在C#6之前将不可用.因此,手动将"Item" 放入代码中可能会带来错误,而 nameof()会在编译时捕获此类错误.>

因此,虽然曾经考虑过直接使用名称的方法冒着风险,但这种风险已经消失,并且略有优势.

尽管

ToString()仍然是基于 MyEnum 类型的变量或表达式输出字符串的唯一方法.

MyEnum.Item.ToString();
nameof(MyEnum.Item);

Which style is preferred? Is there any practical difference between the two?

解决方案

The first is a run-time call that will realise at runtime it needs to return the string "Item", and do so.

The second is another way to write "Item" straight into the code.

The second would be slightly faster, but prior to C#6 would not have been available. To put "Item" in the code manually would have therefore been an optimisation that risked an error, while nameof() would catch such an error at compile-time.

As such while the approach of using the name directly might once have been considered taking a risk, that risk is gone, and it has a slight edge.

ToString() though remains the only way to output the string based on a variable or expression of the MyEnum type.

这篇关于MyEnum.Item.ToString()和nameof(MyEnum.Item)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆