2014-10-04 30 views
1

我正在从Typescript移植到C#的一个小程序。在原来的计划我有一个像这样的很多检查:检查列表项目<T>是否有效

var array: T[] = []; 
if (!array[1234]) { // do something } 

基本上检查,如果1234是一个错误的指数(未定义),或者如果该项目已专门设置为nullfalse由我。

现在,当将其移植到C#时,我基本上用替换T[],但我不知道执行此检查的最快方法是什么,因为如果我使用无效索引,我会得到一个异常。

所以我的问题是,检查nullfalse项目的无效索引和索引的最佳方法是什么?

回答

2

要检查请求的索引是你需要检查myIndex < myList.Count的范围内。

如果Tbool,你可以像你已经做的那样做!myList[ix]

在.NET中,由于bool不能为空,所以不需要检查它是否为空。但是,如果T为空或Nullable<T>bool?,则仍需执行== null检查并检查它是否不是false

如果您使用的是.NET 3.5或更高版本,那么您可以编写一个扩展方法,以使其更容易。这是我鞭策几乎所有案件(也许都是?)的东西。的这是什么一样

public static class ListExtensions 
{ 
    public static bool ElementIsDefined<T>(this List<T> list, int index) 
    { 
     if (index < 0 || index >= list.Count) 
      return false; 

     var element = list[index]; 
     var type = typeof (T); 
     if (Nullable.GetUnderlyingType(type) != null) 
     { 
      if (element is bool?) 
       return (element as bool?).Value; 
      return element != null; 
     } 

     var defaultValue = default(T); 
     // Use default(T) to actually get a value to check against. 
     // Using the below line to create the default when T is "object" 
     // causes a false positive to be returned. 
     return !EqualityComparer<T>.Default.Equals(element, defaultValue); 
    } 
} 

快速概述:

  • 检查该指数的范围内。如果
  • 检查TypeNullable(布尔?INT?等)
  • 如果是,那么我们就必须仔细检查,如果该类型是bool?所以我们可以正确地确定是否false供给和返回基于那。
  • 然后确定数组中的实际值是否为默认值。如果是bool,则默认为false,int0,并且任何引用类型为null

你可以这样调用:

var listBool = new List<bool?>(); 
listBool.Add(true); 
listBool.Add(false); 
listBool.Add(null); 

listBool.ElementIsDefined(0) // returns true 
listBool.ElementIsDefined(1) // returns false 
listBool.ElementIsDefined(2) // returns false 

现在快速的注意,这不会是快如闪电。它可以拆分以处理不同类型的对象,但如果您需要为List<int>List<MyClass>等创建类似的方法,则可以删除或添加逻辑,但是因为我将其定义为使用List<T>,所以此方法将显示所有列表。

1

为了检查正确的索引,只需检查它是否小于数组/列表大小。

int index = 1234; 
List<T> list = new List<T>(); 
if (index < list.Count) { 
} 

对于检查空结合指标检查和无效检查:

index < list.Count && list[index] != null 

(在情况下,如果你有引用类型的数组)

2

现在你正在使用C#和访问到BCL,你应该使用一个字典来处理这种事情。这使您可以有效地添加索引并检查它们是否存在。

例如,假设T为string

var s = new Dictionary<int, string>(); 

s[1234] = "Hello"; 
s[9999] = "Invalid"; 

var firstIndexCheck = s.ContainsKey(1234) && s[1234] != "Invalid"; // true 
var secondIndexCheck = s.ContainsKey(9999) && s[9999] != "Invalid"; // false