[英]CS1503: Argument 1: cannot convert from 'int' to 'byte' C#
private byte[] ParsePatternString(string szPattern)
{
List<byte> list = new List<byte>();
foreach ( string text in szPattern.Split(new char[] { ' ' }) )
{
list.Add((text == "?") ? 0 : Convert.ToByte(text, 16));
}
return list.ToArray();
}
The error happens on list.Add((text == "?")? 0: Convert.ToByte(text, 16));
错误发生在
list.Add((text == "?")? 0: Convert.ToByte(text, 16));
What I am wondering is how what is creating the error, because based on the other questions about a similar issue I tried and it seems to not have worked.我想知道是什么造成了错误,因为基于其他关于我尝试过的类似问题的问题,它似乎没有奏效。
0
is an int
literal. 0
是一个int
字面量。 Just like C, there's no way to specify an integer literal smaller than int
.就像 C 一样,无法指定小于
int
的integer 文字。 The type of a conditional operator is the common type of the two values, thus your expression results in an int
expression and can't be passed to a byte
argument. 条件运算符的类型是两个值的通用类型,因此您的表达式会生成一个
int
表达式,并且不能传递给byte
参数。 You need to cast the expression to byte
using either of the following您需要使用以下任一方法将表达式转换为
byte
list.Add(text == "?" ? (byte)0 : Convert.ToByte(text, 16));
list.Add((byte)(text == "?" ? 0 : Convert.ToByte(text, 16)));
You could use byte.MinValue
in this case:在这种情况下,您可以使用
byte.MinValue
:
private byte[] ParsePatternString(string szPattern)
{
List<byte> list = new List<byte>();
foreach ( string text in szPattern.Split(new char[] { ' ' }) )
{
list.Add(text == "?" ? byte.MinValue : Convert.ToByte(text, 16));
}
return list.ToArray();
}
I have actually never used CSharp before but I think the problem might be that it reads 0 as an int and not a Boolean, and doesn't automatically convert it.实际上我以前从未使用过 CSharp,但我认为问题可能在于它将 0 读取为 int 而不是 Boolean,并且不会自动转换它。 From what I'm reading about it you need to add an explicit cast like this:
根据我正在阅读的内容,您需要添加这样的显式转换:
list.Add((text == "?") ? (byte) 0 : Convert.ToByte(text, 16));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.