我想做一个对象数组,但是我发现这很困难,因为我只是一个使用C#的初学者。我的对象数组非常复杂,因为我在对象中有一个元素,这些元素也需要像这样的对象数组。
array = [
{
"bch": "001",
"branch": "AAA",
"pdaccounts": [
{"Name":"John Doe","Amount":1000.00},...
],
"raccounts": [
{"Name":"John Doess","Amount":1980.56},...
],
"collapse":true
},
...
];有谁可以帮我?
发布于 2018-08-17 02:44:31
有许多方法可以使列表和嵌套列表无效。想象一下这是我的课。我已经包含了一个用于对象初始化器模式的无参数构造函数(尽管它不限于无参数构造函数)、一个接受名称和一个列表对象的构造函数以及一个接受一个名称和一个节点的参数数组的构造函数。
为了简单起见,我已经进行了类引用本身,但显然不需要这样做。
public class Node
{
public Node() // you could pass nothing and set them manually or use the object initializer pattern
{
}
public Node(string name, List<Node> nodes) // you could pass the name and an existing list
{
this.Name = name;
this.Nodes = nodes;
}
public Node(string name, params Node[] nodes) // you could pass the name and a list of items (which can be called like Node("a", node, node, node)
{
this.Name = name;
this.Nodes = nodes.ToList(); // needs using System.Linq; at the top of the file or namespace
}
public string Name { get; set; }
public List<Node> Nodes { get; set; }
}示例:
// object initializer
var childChildChildChildNode = new Node
{
Name = "ChildChildChildChild"
}
// constructor: string name, params Node[] nodes
var childChildChildNode = new Node("ChildChildChild", childChildChildChildNode);
// constructor: string name, List<Node> nodes
var childChildNode = new Node("ChildChild", new List<Node> { childChildChildNode });
// object initializer
var childNode = new Node
{
Name = "Child",
Nodes = new List<Node>()
};
// add items to the list of the child node
childNode.Nodes.Add(childChildNode);
// object initializer for node and list
var parentNode = new Node
{
Name = "Parent",
Nodes = new List<Node> { childNode }
};
// full object initializer
var otherParentNode = new Node
{
Name = "Parent",
Nodes = new List<Node>
{
new Node {
Name = "Child",
Nodes = new List<Node>
{
new Node
{
Name = "ChildChild1"
},
new Node
{
Name = "ChildChild2"
}
}
}
}
};请注意,--这不是一个用数组和嵌套数组初始化对象的方法的详尽列表,只是一些入门的例子。
发布于 2018-08-17 02:21:48
考虑需要在包含这些信息的代码中表示的类/对象。您可能已经习惯了POCO类,如下所示:
public class Human
{
public string Name { get; set; }
public int Age { get; set; }
}像上面的Human示例这样的类可以包含您定义的其他类。注意下面CheeseBurger类中的Cheese属性。
public class Cheese
{
public int SmellFactor { get; set; }
}
public class CheeseBurger
{
public Cheese CheeseType { get; set; }
}这可以很容易地适用于您的每个属性"pdaccounts“和"raccounts”。
https://stackoverflow.com/questions/51887460
复制相似问题