c# - List索引和Array索引的区别

标签 c# arrays string list

在我的应用程序中构造连接字符串时,我遇到了一些相当奇怪的异常。

string basis = "Data Source={0};Initial Catalog={1};Persist Security Info={2};User ID={3};Password={4}";
List<string> info1 = new List<string>(){ "SQLSRV", "TEST", "True", "user1", "pass1" };
string[] info2 = new string[] { "SQLSRV", "TEST", "True", "user1", "pass1" };
// throws exception
Console.WriteLine(String.Format(basis, info1));
// works fine
Console.WriteLine(String.Format(basis, info2));

错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

我的问题是:List 的索引有什么问题?

最佳答案

这与索引无关。在您的第一种情况下,您使用 String.Format 的重载:

public static void Format(string format, object arg);

在第二个你使用这个:

public static void Format(string format, params object[] args);

所以在第一种情况下,您只传递一个 参数。这会导致异常,因为您的格式字符串需要多个参数。

在第二种情况下,您提供了所有参数,因为传递的是一个数组,而不是仅一个List 对象。

关于c# - List索引和Array索引的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37521233/

相关文章:

c# - UWP 应用程序中的自定义主题

C# 字节处理

javascript - 如何在 ReactJs 中打印出用户输入的数组

Java与两个字符串的==比较是假的?

sql - T-SQL 将字符串拆分为多对一关系?

c# - 日期时间.ParseExact 为 : Fri Dec 7 16:36:21 2012

c# - 如何在命令提示符下运行 selenium c# test?

c# - 具有缓存结果的属性或获取方法

C++ 将字符串(带空格)显示为二维数组?

python - 更快的 numpy 数组复制;多线程内存?