gpt4 book ai didi

C# string[] arrayA 在 arrayA[3] 中返回空值

转载 作者:行者123 更新时间:2023-11-30 20:34:38 25 4
gpt4 key购买 nike

我的代码中有很多数组,例如;

string[] arrayA = new string[31];

我需要将数组中的值放入 SQL 数据库

SqlCommand commA = new SqlCommand("INSERT INTO dbo.DatabaseA" +
" (ColumnA) VALUES" +
" (@ColumnA)", connA);
commA.Parameters.Add("@ColumnA", SqlDbType.NVarChar).Value = arrayA[3];

为什么 @ColumnA 返回错误“未提供值”或准确地说是 arrayA[3] = null?我一直认为未分配的 string[] 具有 "" 作为初始值。

如果最初我在 SQLCommand 之前分配了 arrayA[3] = "" 代码工作正常。

有没有办法在不使用 for 循环的情况下用 "" 填充所有 string[] arrayA

最佳答案

根据提供的代码,arrayA[3] 没有赋值,该数组只是值的容器,并将每个值设置为类似于 going default 类型的默认值(字符串)

现在 string 是一个引用类型,字符串的默认值是 null 但是是一个值类型例如,int 的默认值为 0

我们可以很容易地测试这个,例如。

string[] arrayA = new string[31];
var s = arrayA[3]; //is null as string is a reference type

int[] arrayB = new int[31];
var i = arrayB[3]; //equals 0 as default(int) = 0

现在正如评论中所指出的那样,有一些简单的方法可以填充数组并且引用的评论指向 How to populate/instantiate a C# array with a single value?

下面的片段来自上面的答案

public static void Populate<T>(this T[] arr, T value ) {
for ( int i = 0; i < arr.Length;i++ ) {
arr[i] = value;
}
}

这可以通过以下方式调用:

arrayA.Populate("");

所以在通话中:

commA.Parameters.Add("@ColumnA", SqlDbType.NVarChar).Value = arrayA[3];

事实上 arrayA[3] = null

编辑上面的代码片段是一个扩展方法(如方法签名中第一个参数的 this 关键字所示)。这必须在类似于下面的静态类中。

public static class ArrayExtensions
{
public static void Populate<T>(this T[] arr, T value)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = value;
}
}
}

关于问题

Is there a way to populate the all string[] arrayAwith "" without using for loop?

设置数组中所有项的默认值的所有方法都需要某种循环,循环可能是 foreachfor某处。

您还可以创建一个方法,为您创建一个具有默认值的指定大小的数组。

public static T[] CreateArray<T>(int capacity, T defaultValue)
{
var array = new T[capacity];
array.Populate(defaultValue);
return array;
}

然后可以将其称为:

var arrayC = ArrayExtensions.CreateArray<string>(31, "");
s = arrayC[3]; //equals ""

然而,这对我来说开始显得太懒了。

关于C# string[] arrayA 在 arrayA[3] 中返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38886307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com