(該帖子已被編輯的更多的信息,因爲它是簡化的)填充陣列中的物體,在c#
在 System.IndexOutOfRangeException下面的結果的代碼:索引陣列的邊界之外
,我想弄清楚爲什麼會發生這種情況。
該示例有點簡化。
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://iptc.org/std/SportsML/2008-04-01/")]
[System.Xml.Serialization.XmlRootAttribute("team-metadata", Namespace = "http://iptc.org/std/SportsML/2008-04-01/", IsNullable = false)]
public partial class teammetadata
{
private name[] nameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("name")]
public name[] name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://iptc.org/std/SportsML/2008-04-01/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://iptc.org/std/SportsML/2008-04-01/", IsNullable = false)]
public partial class name
{
private string fullField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string full
{
get
{
return this.fullField;
}
set
{
this.fullField = value;
}
}
}
試圖做到這一點:
// Creating team meta data object
var teamMetaData = new teammetadata[1];
// creating home team meta data
var homeTeamMetaData = new teammetadata();
// Creating a new home team name
var homeTeamName = new name[0];
// Creating the team name
var teamName = new name { full = "Team name" };
homeTeamName[0] = teamName; // Ok
homeTeamMetaData.name = new name[] { teamName }; // Causes exception
homeTeamMetaData.name = homeTeamName; // Causes exception
我已經嘗試了一些不同的方法,但每個人都異常結束。
我誤解了什麼?
答案:
作爲帕特里克霍夫曼正確地指出,我設置homeTeamName與設置爲零的大小空數組。在陣列中,你在1設置大小起點,但加入的項目,當你在位置0
萬一別人絆倒這個開始爲好,這裏是一個很簡單的例子來告訴數組是如何工作的:
using System;
public class Program
{
public static void Main()
{
// Creating an array of strings which can hold up to two string objects
var arrayString = new string[2];
// Creating the first string object
var stringItem1 = "Hello";
// Adding the first string object to the array
arrayString[0] = stringItem1;
// Creating the second string object
var stringItem2 = "World!";
// Adding the second string object to the array
arrayString[1] = stringItem2;
// Write the output...
Console.WriteLine(arrayString[0] + " " + arrayString[1]);
}
}
這個例子也可以在這裏找到:
https://dotnetfiddle.net/JpJyDg
再次,感謝從堆棧溢出社會非常寶貴的反饋意見和援助。
特朗德
你可以顯示'bar'的類定義嗎? – fubo
對我來說,這段代碼編譯並運行得很好。顯然你過分簡化代碼(除了'codeFoo [0]'不包含任何名爲'bar'的成員)。 – HimBromBeere
爲什麼不用'public bar [] barfield {get; set}'? – Aht