c# - 无法将 int 转换为 byte

标签 c# int substring byte delphi-7

我正在将 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,计数:整数):字符串;

然后 strtointstring 转换为 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/

相关文章:

c - 宽度不兼容的变量

java - 将 String 数组转换为 int 值并将其存储在 int 数组中

c# - Int 到字符串 : cannot convert from 'method group' to 'string'

java - 我需要使用子字符串,但我需要包含第二个参数

MYSQL JOIN ON X = IF(A,B,C) 条件

c# - 在 WPF 应用程序中动态创建按钮列表

c# - 如何在 Visual Studio C# 中制作图表动画?

c# - 使用 C# 限制在一行上打印的项目数

c# - 如何在 C# 中搜索多个位置的直接子字符串

c# - 带有 SqlServerCe.3.5 的 Entity Framework - 连接异常