我目前正尝试在我的类定义中实现一个“索引”的属性。
例如,我有以下类:
public class TestClass
{
private int[] ids = null;
public string Name { get; set; }
public string Description { get; set; }
public int[] Ids {
get
{
//Do some magic and return an array of ints
//(count = 5 - in this example in real its not fixed)
return _ids;
}
}
}
现在我想要使用这个类如下:
private void DoSomething()
{
var testClass = GetSomeTestClass();
//work with the ids
for (int i = 0; i < 10; i++) //I know I could say i < Ids.Length, its just an example
{
int? id = testClass.Ids[i];
//this will result, in a out of bound exception when i reaches 5 but I wish for it to return a null like a "safe" index call ?!?
}
}
是否有一种安全的索引调用,可以返回null,而不需要我一遍又一遍地包装它在 try catch 中。
另外,我不想使用类索引,因为我需要多个属性像这样工作,具有不同的类型(int、string、bool、自定义类等)。
(再次说明for只是一个简单的例子,我知道在这种情况下可以说“i < Ids.Length”)
null
?这样有所改善吗? - JonT
用作Nullable<T>
参数。不过我正在寻找替代方案... - James