C#结构数组分配 [英] C# struct array assignment
问题描述
我已经在C#中定义了一个结构.在此结构中,我有一个整数数组.此字段是ImagesLoadStatus,如下所示.
Hi,
I have defined a struct in C#. Inside this struct I have an array of integers. This field is ImagesLoadStatus as below.
struct ProductImages
{
public string ImageB;
public string ImageS;
public string ImageOrg;
public int[] ImagesLoadStatus;
}
在另一个类中,我正在初始化数组.此处:
In another class I am initializing the array. Here:
ProductImages prdImages = new ProductImages();
for (int i = 0; i < 4; i++)
prdImages.ImagesLoadStatus[i] = 0;
我构建应用程序没有错误.但是出现一条警告消息,提示:
警告CS0649:字段"ProjectName.ClassFolder.ProductImages.ImagesLoadStatus"从未分配给其,并且始终具有其默认值null
我已经在结构体中初始化了他的数组,为什么我会收到这样的警告消息?
在此先感谢
I build the application without error. But a warning message appears saying :
warning CS0649: Field ''ProjectName.ClassFolder.ProductImages.ImagesLoadStatus'' is never assigned to, and will always have its default value null
I am already initializing he array in the struct, why do I get such a warning message ?
Thanks in advance,
推荐答案
数组本身从未初始化.您也需要这样做.
示例:
The array itself is never initialized. You need to do that too.
Example:
ProductImages prdImages = new ProductImages();
prdImages.ImagesLoadStatus = new int[ProductImages.MAXBUFFER];
int initValue = 7; // arbitrary example
int minCount = 5; // arbitrary example
for (int i = 0; i < Math.Min(minCount, prdImages.ImagesLoadStatus.Length); i++)
prdImages.ImagesLoadStatus[i] = initValue;
使用数组时,您正在为各个元素分配值.
When you use the array, you are assigning values to the individual elements.
prdImages.ImagesLoadStatus[i] = 0;
但是,您没有分配实际的数组.添加一行:
However, you do not assign the actual array. Add the one line:
ProductImages prdImages = new ProductImages();
prdImages.ImagesLoadStatus = new int[myArraySize]; // Add this line.
for (int i = 0; i < prdImages.ImagesLoadStatus.Length; i++)
prdImages.ImagesLoadStatus[i] = 0;
应该没问题.
[edit]将循环保护更改为数组大小-OriginalGriff [/edit]
And it should be fine.
[edit]Changed loop guard to array size - OriginalGriff[/edit]
您的初始代码或您的构造函数应真正创建此数组并设置默认值,该代码本身非常脆弱并要求所有用户检查null等.
Your initial code or your constructor should really create this array and set default values, the code as it stands is quite fragile and requires all users to check for null, etc.
这篇关于C#结构数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!