我不确定我是否以正确的方式使用struct。无论如何,我需要一个结构,其中一个属性是一个由另一个结构组成的数组。不知怎的,我无法接近嵌套结构中的一个属性。
struct Clients
{
int client_number;
public ArrayList accounts;
}
struct JsonStruct
{
public ArrayList clients;
}
var obj = new JsonStruct();
obj.clients[0] = new Clients();
obj.clients[0].client_number = 100; // this last line does not work..
/* it throws this kind of error:
"object does not contain a definition for client_number.."
*/
obj.clients [0]现在应该有客户端的结构,但它似乎没有。
在阅读OP的评论和要求后,我找到了这个解决方案:
using System;
using System.Collections.Generic;
public class structCheck
{
public static void Main(string[] args)
{
var obj = new JsonStruct();
obj.clients.Add(new Clients());
obj.clients[0].client_number = 100;
Console.WriteLine(obj.clients[0].client_number);
}
}
class Clients
{
public int client_number;
public List<int> accounts = new List<int>();
}
class JsonStruct
{
public List<Clients> clients = new List<Clients>() ;
}
OUTPUT:
100
如果你想添加一些东西,请告诉我。
你需要改变4件事:
client_number
公开,否则您的代码无法访问它((Clients) obj.clients[0]).client_number = 100;
。由于ArrayList包含object
类型的项目,因此必须将它们转换回Clients
Make新代码如下所示:
using System;
using System.Collections;
using System.Collections.Generic;
class Clients
{
public int client_number;
public ArrayList accounts; // maybe you ma want to change this to a list<T> as well
}
class JsonStruct
{
public List<Clients> clients;
}
var obj = new JsonStruct();
obj.clients[0] = new Clients();
obj.clients[0].client_number = 100;