我正在开发一个解决学校Rubiks Cube的程序,有一个我无法修复的错误:我有一个带有get和set访问器的属性(Array)。为了尽早避免可能的错误,我会在将每个Object添加到Array之前检查它们。 为此我使用两个foreach循环:一个用于每个单个对象,一个用于已添加的所有对象(用于检查对象是否被添加两次,这是不允许的)。问题是,即使我检查给定的数组长度,我得到一个NullRefernceException,说foreach循环选择的当前对象为null。怎么可能呢?
这是属性:
private cCubePart[] permutation;
public cCubePart[] Permutation
{
get { return permutation; }
set
{
if (value.Length == 27)
{
bool valid = true;
List<string> id = new List<string>();
foreach (cCubePart cp in value)
{
foreach (string s in id)
{
if (s == cp.StringID)
{
valid = false;
}
}
if (valid)
{
id.Add(cp.StringID); //That's where the Exception is thrown; cp is null
}
}
if (valid)
{
permutation = value;
}
else
{
throw new Exception("The Permutation you were trying to set contains cCubePart objects with the same id!");
}
}
else
{
throw new Exception("The Permutation you were trying to set doesn't fit the requirements!");
}
}
}