[英]How to assign data in an ArrayList from another class in c#
arraylist
數據? public class PlatanoJson //this is first class where arraylist is declared
{
public string question { get; set; }
public string correctans { get; set; }
public bool typeofans { get; set; }
public int indexofque { get; set; }
public ArrayList DiffAns = new ArrayList();
}
public class JsonSerializationController : ApiController
{
[Route("getjsondata")]
public string jsonDataToSerialize()
{
var game = new PlatanoJson {
question = "What is your education?",
correctans = "MCA",
typeofans = true,
indexofque = 3,
DiffAns = //how to add data here??
};
var result = Newtonsoft.Json.JsonConvert.SerializeObject(game);
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<PlatanoJson>(result);
return (" Question="+dresult.question+" Correct Answer="+dresult.correctans+" Type of ans="+dresult.typeofans+" Index of Que"+dresult.indexofque+" Answers choice="+dresult.DiffAns);
}
}
由於ArrayList
不會對包含的數據做任何假設,因此可以向其中添加任何數據類型。 為此,有幾種可能性,例如使用對象初始化程序:
var game = new PlatanoJson {
question = "What is your education?",
correctans = "MCA",
typeofans = true,
indexofque = 3,
DiffAns = new ArrayList { 1, 2, 3, "myString" }
};
另外,您也可以使用期望ICollection
的構造函數:
DiffAns = new ArrayList(new object[] { 1, 2, 3, "myString" })
但是,我建議您花些時間並改用通用方法。 使用ArrayList
您無法限制列表中可能包含的對象,可以(如在上面的代碼中看到的)將inetegeres,字符串和任何其他數據類型放入其中。 更好地使用List<T>
,它為您提供編譯時類型安全性:
var game = new PlatanoJson {
question = "What is your education?",
correctans = "MCA",
typeofans = true,
indexofque = 3,
DiffAns = new List<int>{ 1, 2, 3 } // you van´t put a string into this list
};
您為什么不將代碼更改為以下內容(如果列表包含字符串)。
public class PlatanoJson //this is first class where arraylist is declared{
public string question { get; set; }
public string correctans { get; set; }
public bool typeofans { get; set; }
public int indexofque { get; set; }
public List<string> DiffAns { get; set; }
}
public class JsonSerializationController : ApiController
{
[Route("getjsondata")]
public string jsonDataToSerialize()
{
var list= new List<string>();
list.Add("your stuff1");
list.Add("your stuff2");
list.Add("your stuff3");
var game = new PlatanoJson {
question = "What is your education?",
correctans = "MCA",
typeofans = true,
indexofque = 3,
DiffAns = list;
};
var result = Newtonsoft.Json.JsonConvert.SerializeObject(game);
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<PlatanoJson> (......................
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.