現在、クラス定義内に「インデックス付き」プロパティを実装しようとしています。
たとえば、次のクラスがあります。
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 ?!?
}
}
したがって、try catch で何度もラップする必要なく、null になる安全なインデックス呼び出しはありますか。
クラスインデックスを使用したくないもう1つのことは、このように機能するさまざまなタイプ(int、string、bool、カスタムクラスなど)のプロパティがいくつか必要なためです。
(繰り返しますが、for は単純な例にすぎません。この場合、「i < Ids.Length」と言えます)