我对编码C#有点新意,我试图找到一种方法来轻松访问以下值:
项[CURRENTITEM] .sellOrder [0] .POSITION
但是,由于我从未在课程和C#上工作太多,我有点迷失,不知道为什么这不起作用或我做错了什么。有人可以给我一些帮助吗?
public class Item {
public int Pos {get;set;}
public string Name {get;set;}
public int Placement {get;set;}
public int socount = 0;
public class sellOrder {
public int Position {get;set;}
public int Quantity {get;set;}
public float Price {get;set;}
public sellOrder(int p, int q, float v) { Position = p; Quantity = q; Price = v; }
}
sellOrder[] sellOrderList;
public Item(int p, string n) { Pos = p; Name = n; Placement = -1; }
public void addSellOrder(int p, int q, float v) {
sellOrderList[socount] = new sellOrder(p, q, v);
socount++;
}
}
样品:
Item[] item;
item = new Item[1];
item[0] = new Item(0, "testitem");
item[0].addSellOrder(1, 2, 10.2);
但是当我尝试访问 item [currentItem] .sellOrder [0] .Position 时,我得到:
错误CS0119:' Item.sellOrder'是一种类型,在该类型中无效 给定上下文
提前谢谢你,问候
答案 0 :(得分:2)
您的收藏存储在属性sellOrderList
中,因此请使用此属性进行访问:
item[currentItem].sellOrderList[0].Position
修改强>:
要允许从sellOrderList
类外部访问Item
,您必须使此属性public
(或可能internal
)。也许你也想为此提供一个getter和setter。
public sellOrder[] sellOrderList { get; set; }
答案 1 :(得分:1)
您可以封装一个列表并将其公开为数组(仅适用于readonly propouses)。有关示例(请参阅注释。我也重构了您的代码):
public class Item {
public int Pos { get; set; }
public string Name { get; set; }
public int Placement { get; set; }
// define a private list
private List<SellOrder> _sellOrders;
// define a property to encapsulate and return the list as an array, just for readonly
public SellOrder[] SellOrderList { get { return _sellOrders.ToArray(); } }
public Item(int p, string n) {
Pos = p;
Name = n;
Placement = -1;
// init the list on the constructor
_sellOrders = new List<SellOrder>();
}
// add elements on the list
public void addSellOrder(int p, int q, float v) {
_sellOrders.Add(new sellOrder(p, q, v));
}
public class SellOrder {
public int Position { get; set; }
public int Quantity { get; set; }
public float Price { get; set; }
public sellOrder(int p, int q, float v) {
Position = p;
Quantity = q;
Price = v;
}
}
}
要访问它,您可以使用:
var position = item[currentItem].SellOrderList[index].Position;