我正在寻找一种方法将4个一维数组输入到4x4多维数组中。
在我寻找这个的时候,我发现使用锯齿状数组似乎更简单。但是,我觉得我错过了一些明显的东西,并希望寻求帮助。
for (int x = 0; x <= 3; x++)
{
//reads in 4 separate values e.g. A B C D
unitReader = sr.ReadLine();
//creates a char array with 4 separate elements
char[] line = unitReader.ToCharArray();
//places that array into a bigger jagged array
fullArray[x] = line;
//just to test that it's worked
Console.WriteLine(fullArray[x]);
}
这就是我用前面定义的锯齿状数组的方法:
char[][] fullArray = new char[4][];
是否有类似于此的代码允许我按行将值分配给多维数组,而不必执行16次传递来分配单个元素?
答案 0 :(得分:0)
我认为您正在寻找 Buffer.BlockCopy()
有关详细信息,请参阅Documentation of BufferCopy.BlockCopy
答案 1 :(得分:0)
对于可扩展性,您可以尝试像这样的自定义集合
public class FixedSizeCollection<T> : Collection<T>
{
protected bool _initializing;
public int Size { get; private set; }
public FixedSizeCollection(int size)
{
Size = size;
Init();
}
public FixedSizeCollection(int size, IList<T> list)
{
Size = size;
Init();
if (list.Count != Size)
throw new InvalidOperationException("Changing size is not supported.");
foreach (T item in list)
Items[list.IndexOf(item)] = item;
}
protected virtual void Init()
{
_initializing = true;
base.ClearItems();
for (int j = 0; j < Size; j++)
Add(default(T));
_initializing = false;
}
protected override void ClearItems()
{
Init();
}
protected override void InsertItem(int index, T item)
{
if (!_initializing)
throw new InvalidOperationException("Changing size is not supported.");
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
if (!_initializing)
throw new InvalidOperationException("Changing size is not supported.");
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
base.SetItem(index, item);
}
}
public class SquareArray<T> : FixedSizeCollection<FixedSizeCollection<T>>
{
public SquareArray(int size) : base(size)
{
}
protected override void Init()
{
_initializing = true;
for (int i = 0; i< Size; i++)
{
FixedSizeCollection<T> row = new FixedSizeCollection<T>(Size);
Add(row);
}
_initializing = false;
}
protected override void SetItem(int index, FixedSizeCollection<T> item)
{
if (item.Count != Size)
throw new InvalidOperationException("Changing size is not supported.");
base.SetItem(index, item);
}
}
然后你的循环看起来像那样:
SquareArray<char> fullarray = new SquareArray(4);
for (int x = 0; x <= 3; x++)
{
//reads in 4 separate values e.g. A B C D
unitReader = sr.ReadLine();
//creates a char array with 4 separate elements
char[] line = unitReader.ToCharArray();
//places that array into a bigger jagged array
fullArray[x] = new FixedSizeCollection(4, line);
//just to test that it's worked
Console.WriteLine(fullArray[x]);
}