简体   繁体   English

在C#元组中使用Int64

[英]Use an Int64 in C# Tuple

I'm sure this is something simple, but I'm getting a compiler error when using the .Create() method of the new Tuple class. 我确定这很简单,但是使用新的Tuple类的.Create()方法时出现编译器错误。

Dictionary<long, Tuple<long, long>> test = new Dictionary<long, Tuple<long, long>>();
test.Add(1, Tuple.Create(1, 2)); // <-- compiler error

The error is that Tuple.Create has invalid arguments, as it is expecting longs, and the numbers I've put in are being considered as integers. 错误是Tuple.Create具有无效的参数,因为它期望longs,而我输入的数字被视为整数。

In this case yes they are within the range of int, but they may may sometimes have a value too big for an int. 在这种情况下,它们在int范围内,但是对于int而言,它们有时可能值太大。

I could cast (long)1 to get the code to compile, but this doesn't seem right - what am I missing? 我可以强制转换(long)1来编译代码,但这似乎并不正确-我缺少什么?

Use the L suffix to specify that you want your numbers to be of type long : 使用L后缀指定您希望数字为long类型:

test.Add(1, Tuple.Create(1L, 2L));

Without the suffix, .NET assumes these numbers to be int s and thus creates a Tuple<int, int> instance instead of the desired Tuple<long, long> . 不带后缀,.NET假定这些数字为int ,因此创建了Tuple<int, int>实例,而不是所需的Tuple<long, long>

Your code is equivalent: 您的代码是等效的:

Tuple<long, long> yourTuple = Tuple.Create(1, 1);

But, because 1 can be either int or long , so by default, compiler will return Tuple<int, int> when calling: 但是,由于1可以是intlong ,所以默认情况下,编译器在调用时将返回Tuple<int, int>

 Tuple.Create(1, 1)  

That is why you get compiler error. 这就是为什么会出现编译器错误。 Therefore, you need to make casting explicitly by using generic version: 因此,您需要使用通用版本进行显式转换:

Tuple.Create<long, long>(1, 1);

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

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