下划线在C#中的数字文字中是什么意思? [英] What do the underscores mean in a numeric literal in C#?

查看:88
本文介绍了下划线在C#中的数字文字中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,下划线的意义是什么:

In the code below what is the significance of underscores:

public const long BillionsAndBillions = 100_000_000_000;

推荐答案

这是C#7.0的新功能,被称为数字分隔符.目的是提供更好和更容易的可读性.当编写在源代码中非常长且难以阅读的数字时,它最有用.例如:

This is a new feature of C# 7.0 and it is known as digit separator. The intent is to provide better and easier readability. It is mostly useful when writing numbers that are very long and hard to read in source code. For example:

long hardToRead = 9000000000000000000; 

// With underscores
long easyToRead = 90000_00000_00000_0000;  

完全由程序员决定下划线的放置位置.例如,您可能会遇到如下奇怪的情况:

It is totally up to the programmer on where to place the underscore. For example, you may have a weird scenario like this:

var weird = 1_00_0_0_000_0000000_0000;  
public const decimal GoldenRatio = 1.618_033_988_749_894_848_204_586_834_365_638_117_720M;


一些注释

编译代码后,编译器会立即删除下划线,这仅是为了提高代码的可读性.这样的输出:

As soon as you compile your code, the compiler removes the underscores so this is just for code readability. So the output of this:

public static void Main()
{
    long easyToRead = 90000_00000_00000_0000;
    Console.WriteLine(easyToRead);
}

将是(注意没有下划线):

will be (notice no underscores):

9000000000000000000

< ==尝试我!==>

此处是有关您何时有兴趣请求此功能的讨论.有些人希望分隔符为空白空格,但是看起来C#团队使用了下划线 s.

Here is a discussion about when this feature was requested if you are interested. Some people wanted the separator to be blank spaces, but looks like the C# team went with underscores.

这篇关于下划线在C#中的数字文字中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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