在 C# 中为短数据类型转换错误
Cast error in C# for datatype short
一个关于C#中int和short的基本问题
为什么我收到此代码的语法错误:
for (short i = 0; i < list.Length; i++)
{
short key = i + (short)1; //This is where I get error
//Can not implicitly convert 'int' to 'short'
//Some more code, dealing with this key...
}
有什么好的 table 显示不同类型及其初始化快捷方式的地方吗?
(像var f = 1M;
会编译成十进制)
修改以下内容,
short key = i + (short)1;
至
short key = (short) (i + (short)1);
原因是,short + short 的任何添加都可能溢出短程。因此这需要显式转换。
这样试试:
short key = (short) (i + (short)1);
另请注意,Int16
变量在添加时会转换为 Int32。
您还可以阅读 Eric Liperts 的回答:
- Integer summing blues, short += short problem
一个关于C#中int和short的基本问题
为什么我收到此代码的语法错误:
for (short i = 0; i < list.Length; i++)
{
short key = i + (short)1; //This is where I get error
//Can not implicitly convert 'int' to 'short'
//Some more code, dealing with this key...
}
有什么好的 table 显示不同类型及其初始化快捷方式的地方吗?
(像var f = 1M;
会编译成十进制)
修改以下内容,
short key = i + (short)1;
至
short key = (short) (i + (short)1);
原因是,short + short 的任何添加都可能溢出短程。因此这需要显式转换。
这样试试:
short key = (short) (i + (short)1);
另请注意,Int16
变量在添加时会转换为 Int32。
您还可以阅读 Eric Liperts 的回答:
- Integer summing blues, short += short problem