初始化c#数组为其索引值,而无需循环或递归? [英] Initialize c# array to its index value without loops or recursions?
本文介绍了初始化c#数组为其索引值,而无需循环或递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我知道C#首次初始化时会将数组初始化为default(T).
(int [] ar = new int [n]);
有什么方法可以初始化数组:
a [0] = 0
a [1] = 1
...
a [n] = n
没有任何循环或递归?
谢谢
顺便说一句,我的解决方案与此类似:
hey, i know that C# inits the array to the default(T) when is first initialized.
(int[] ar = new int[n]);
is there any way to initialize the array:
a[0] = 0
a[1] = 1
...
a[n] = n
without any loops or recursion?
thanks
by the way, my solution was similar to this:
public class intArray
{
int[] arr;
bool[] gotArray;
public intArray(int size)
{
arr = new int[size];
gotArray = new bool[size];
}
// dont remember exactly the [] syntax but:
public int operator [](int index)
{
get
{
if (!gotArray[index])
return index;
else
return arr[index];
}
set
{
arr[index] = value;
gotArray[index] = true;
}
}
}
但似乎有更好的解决方法
but it seems that there''s a better solution
推荐答案
您可以使用可为空的int
来剪切原始数组中的bool数组.
You could cut out the bool array in your original by using a nullable int
public class intArray
{
int?[] arr;
public intArray(int size)
{
arr = new int?[size];
}
public int this[int index]
{
get
{
if (arr[index] == null)
arr[index] = index;
return (int)arr[index];
}
set
{
arr[index] = value;
}
}
}
class Program
{
static void Main(string[] arguments)
{
intArray iarr = new intArray(10);
for (int i = 0; i < 10; ++i)
Console.Out.WriteLine(iarr[i]);
Console.ReadKey();
}
}
您的意思是:
You mean something like:
int[] ar = new int[3] { 0, 1, 2 };
int[] ar = new int[3];
ar.Initialize();
这篇关于初始化c#数组为其索引值,而无需循环或递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文