我正在将 Delphi 应用程序转换为 C#,我遇到了这个:
alength:=1; //alength is a byte
aa:=astring //astring is a string parameter passed into the function containing all this
alength:=strtoint(copy(aa,2,length(aa)-1));
所以 copy
从现有字符串的一部分创建一个字符串,字符串的第一个字符从索引 1
开始,而不是 0
像其他语言一样。它使用这种格式:
函数复制(来源:字符串;StartChar,计数:整数):字符串;
然后 strtoint
将 string
转换为 int
。
对于那段代码的 C# 转换,我有:
alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));
这给了我错误 Error 131 Cannot implicitly convert type 'int' to 'byte'。存在显式转换(是否缺少强制转换?)
因为 alength
已经是 byte 类型,我不认为我必须强制转换它?
最佳答案
当您分配一个字节时,您正在使用 Convert.ToInt32()
。请改用 Convert.ToByte()
。
更好的方法是使用 TryParse
来避免在字符串无效时出现异常:
byte alength;
bool success = Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength);
如果解析成功success
为true,否则为false。
您可以根据转换是否成功来定义程序的流程:
byte alength;
if(Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength))
{
//Great success! continue program
}
else
{
//Oops something went wrong!
}
关于c# - 无法将 int 转换为 byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35506066/