简体   繁体   English

在C#中,整数文字是什么类型?

[英]In C# what type are integer literals?

I just notice if i pass a value such as 1 in a function parameter it will work if it excepts int, long and i assume the others. 我只是注意到,如果我在函数参数中传递一个值(例如1),它将可以正常工作,除非它是int,long且我假设其他值。 However if i do int i = value, it doesnt. 但是,如果我做int我=值,它没有。 I was wondering, what type is it? 我想知道是什么类型的?

(1).GetType().ToString() //is System.Int32

Take a look at the integer literals specification : 看一下整数文字规范

The type of an integer literal is determined as follows: 整数文字的类型确定如下:

  • If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong. 如果文字没有后缀,则具有可以表示其值的以下类型中的第一个:int,uint,long,ulong。
  • If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong. 如果文字以U或u结尾,则具有可以表示其值的第一种类型:uint,ulong。
  • If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong. 如果文字以L或l为后缀,则具有可以表示其值的第一种类型:long,ulong。
  • If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. 如果文字的后缀为UL,Ul,uL,ul,LU,Lu,lU或lu,则其类型为ulong。

You can suffix literal integers to make the type explicit, otherwise the value will be implicitly interpreted as though it were the target type (assuming it doesn't overflow the target). 您可以给文字整数加上后缀以使类型显式,否则值将被隐式解释为目标类型(假设它不会使目标溢出)。

var myLong = 123L;
var myInt = 123;
var myByte = (byte)123; // i'm not aware of a suffix for this one

// unsigned variants
var myULong = 123UL;
var myUInt = 123U;

据我了解,编译器将在编译时使用类型提示来确定文字的类型。

The type is determined. 确定类型。

If you have this function: 如果具有此功能:

public void SomeFunc( long i );

and you call it like this: 您这样称呼它:

SomeFunc (1);

Then C# will see this '1' as being a long. 然后,C#将看到这个“ 1”很长。

整数文字是int每默认的,但因为有一个从隐式转换intlong ,你仍然可以调用它采取的方法longint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM