0

我们可以在通用列表中进行类型转换,例如在字符串中创建列表并尝试添加和检索 int 值...例如:

class Program
{
    static void Main()
    {
    List<int> list = new List<int>();
    list.Add(2);
    list.Add(3);
    list.Add("prakash");
    list.Add("arun");
    }
    for (int i = 0; i < list.Count; i++) // Loop through List with for
    {
        Console.WriteLine(list[i]);
    }
}
4

1 回答 1

0

不,您不能将字符串添加到通用List<int>. 正如 Dmitry 指出的那样,您可以int在添加字符串之前尝试解析字符串。

您可以将 if 语句与 TryParse 一起使用,如下所示。

int theNumber;
if (int.TryParse("prakash", out theNumber))
{
    list.Add(theNumber);//Will not be added 
}

if (int.TryParse("42", out theNumber))
{
    list.Add(theNumber);//Will be added
}
于 2017-04-17T12:36:07.117 回答