【发布时间】:2013-11-17 12:24:12
【问题描述】:
我目前正在尝试在我的类定义中实现“索引”属性。
例如我有以下课程:
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
【问题讨论】:
-
编写这样的代码很容易,但你应该质疑你的动机。 所有健全的数据结构为您提供了确定索引访问是否合法的方法,而无需诉诸
try/catch。为什么要推出自己的“越界处理”而不是使用现有设施? -
在输入第 100 个 if 语句检查它是否在边界后,我厌倦了它,想问这样的事情是否可能。我知道这不是标准行为,但我想也许有办法做到这一点。可能是静态扩展什么的,我不知道。
-
您厌倦了它并决定检查结果是否为
null?这在某种程度上是一种改进吗? -
不是真的,因为在我的应用程序中,我不在乎它是 null 还是 int。我只想将一个数组项传递给一个可为空的类型变量,几秒钟前的答案中有一个扩展方法对我来说已经足够了,但是它被删除了。 :(
-
@RandRandom 我删除了我的答案,因为不幸的是你不能使用
T作为Nullable<T>参数。我正在研究另一种方法......
标签: c# .net properties indexing