问题描述
在我的程序中,我有一个 treeView
.在我正在处理的部分中,节点的 displayNames
是数字 integer
值,但显示为 strings
.在我的程序中,我需要将这些 displayNames
转换并临时存储在一个 integer
变量中.我通常使用 Regex.Match()
来做到这一点,没有问题,但在这种情况下,我收到编译器错误:不能隐式将类型 'string' 转换为 'int'
.
In my program I have a treeView
. In the section that I am working with, the node's displayNames
are numerical integer
values, but are displayed as strings
. I have come to a point in my program where I need to convert and temporarily store these displayNames
in an integer
variable. I usually use Regex.Match()
to do this with no problem, but in this scenario I am getting the compiler error: Cannot implicitly convert type 'string' to 'int'
.
这是我的代码:
//This is the parent node as you may be able to see below
//The children of this node have DisplayNames that are integers
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
for (int i = 0; i < node.Children.Count(); i++)
{
//Error on this line!!**
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, @"\d+").Value;
}
}
*注意:DisplayName.Value
是一个 string
推荐答案
从string到int,使用int.Parse(string),它返回传入的string所代表的int,如果输入格式不正确则抛出.
To get from string to int, use int.Parse(string), it returns the int represented by the passed string and throws if the input format is incorrect.
int.Parse(node.Children.ElementAt(i).DisplayName.Value)
如果您不想抛出,也可以使用 int.TryParse.在这种情况下,您将使用:
You can also use int.TryParse if you don't want the throw. in that case you would use:
int parsedValue;
if (int.TryParse(node.Children.ElementAt(i).DisplayName.Value, out parsedValue))
{
///Do whatever with the int
}
这篇关于将字符串转换为 int 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!