在我的应用程序中构造连接字符串时,我遇到了一些相当奇怪的异常。
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/