2016-12-02 56 views
-3

我宣布我的数组像这样使用数组,中如果知道情况,如果该指数是在C#空

string[] timeArrivalArray = new string[10]; 

现在,让我们假设每点击添加按钮,东西插入那里。

但是我想使用if条件到某个索引。 我想用这样的

if (timeArrivalArray[] == [2]) { 
} 

现在,每当我点击button,则timeArrivalArray[]会检查它是否已经在第二个索引,然后执行代码。 tl; dr我只想使用if条件到第二个索引,这怎么可能?

编辑
我的问题是它在第一个增量中抛出excemption。我有一个button和从某些变量插入的东西。然而,上面的代码插入到该

if (timeArrivalArray[] == [2]) { 
    //*insert variable this* 
} else { 
    // *insert variable that* 
} 

编辑2
是的,它不是正确的语法,我只知道如何做到这一点。但我的问题的根源是这

DateTime theCalcu = DateTime.ParseExact(timeArrivalArray[2], "h:mm tt", System.Globalization.CultureInfo.InvariantCulture); 

它扔我String reference not set to an instance of a String. 也许是因为他无法找到任何索引前面的索引。 任何建议都可以。

+0

目前还不清楚你在问什么。请添加一个代码,显示按钮应该执行的操作,并重新说明问题并说明问题所在。 –

+0

我不明白这一点。你只是想像'if(timeArrivalArray [2] ==“无论”)'? – Jens

+0

先生们,我编辑了我的问题。对于这个问题抱歉,但我不能直想。 – Fiendcoder1

回答

0

尽管我可以从你的帖子理解这里是我能想到的逻辑。你可以让我知道什么不起作用。

string[] timeArrivalArray = new string[10]; 
public void Button1_Click(object sender, EventArgs e) 
     { 
      if (timeArrivalArray[2] == null) 
      { 
       //keep inserting into the array since 2nd index is null 
      } 
      else if (timeArrivalArray[2] != null && timeArrivalArray[2] == "someInputValue") 
      { 
       //2nd index is non null and some existing value found 
       //so do something else 
      } 
      else 
      { 
       //2nd index isn't null but input value wasn't found so keep inserting 
      } 
     } 
+0

检查null并不是很有用,因为C#的'new'会将所有数组初始化为空字符串。 – t0mm13b

+2

Nope @ t0mm13b。他们将被初始化为null。字符串是一个引用类型。 – RBT

+1

woop ...我的坏,仍然会更好地使用'String.IsNullOrEmpty' [MSDN](https://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx) – t0mm13b

0

每当我按一下按钮。 timeArrivalArray []将检查它是否已经在第二个索引[...]我只是想使用第二个索引的if条件

这听起来像你想要每次计算索引发生点击。如果是这样,你应该指定一个索引变量超出单击事件的范围:

string[] timeArrivalArray = new string[10]; 

int index = 0; 

public void Button1_Click(object sender, EventArgs e) 
{ // make sure you are not running out of bounds  
    if(index < timeArrivalArray.Length) 
    {  
     if(index == 2) 
     { 
      timeArrivalArray[index] = //*insert variable this* 
     } 
     else 
     { 
      // *insert variable that* 
     }   
    } 

    index ++; // walk to the next position  
}