B. *_*non 1 c# arrays null arraylist
如果我有这个:
int[] lstAFewInts = new int[NUMBER_OF_STARS_IN_THE_MILKY_WAY];
Run Code Online (Sandbox Code Playgroud)
...我想退出一个方法,如果它没有分配给它的值,我该如何测试呢?是吗:
if (lstAFewInts[0] == null)
Run Code Online (Sandbox Code Playgroud)
...要么???
我的建议是:提高抽象层次.
class LazyArray<T>
{
private T[] array;
private int size;
public LazyArray(int size) { this.size = size; }
public bool IsInitialized { get { return this.array != null; } }
public T this[int x]
{
get
{
return this.array == null ? default(T) : this.array[x];
}
set
{
if (this.array == null) this.array = new T[size];
this.array[x] = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你完成了:你有一个任意大小的数组,你知道它是否已被使用:
void M()
{
var myArray = new LazyArray<int>(whatever);
while(whatever)
{
if (whatever) myArray[whatever] = whatever;
}
if (myArray.IsInitialized)
whatever;
}
Run Code Online (Sandbox Code Playgroud)
default(T) // i.e., default(int)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,将为您提供给定类型的默认值int.但是,作为int值类型,无法区分默认值0和指定值0.
你确定你能以最好的方式解决这个问题吗?Dictionary<something, int>如果某个东西已被分配,那么像某个东西会让你更好地理解,因为如果没有密钥就不会存在.这当然假设你有唯一的钥匙使用,但从你的常数的名称来判断,这个星的名字可能是一个很好用的钥匙.
也...
int[] lstAFewInts = new int[NUMBER_OF_STARS_IN_THE_MILKY_WAY];
Run Code Online (Sandbox Code Playgroud)
我们银河系中的恒星数量估计约为1000亿颗.这是你分配的大约400GB.我看到你在不久的将来内存不足:)
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |