在C#中声明的对象与X,Y paramateres [英] declare object in c# with x,y paramateres
问题描述
我要创建的对象A,这将有X,Y参数。
和A必须是一个数组。什么是申报和建设这样的对象的最佳实践?例如这样的事情:
I want to create object "A" which will have x, y parameters. and A must be an array. What's best practice of declaring and constructing such object ? for example something like this:
A[0].x=5
A[0].y=3
A[1].x=6
A[1].y=4
更新
我所做的是这样的:
Update I've done this way:
public class PersonalWaypoints
{
public float x { get; set; }
public float y { get; set; }
}
public class MainClass:MonoBehaviour
{
then in void Start() {
PersonalWaypoints[] pw = new PersonalWaypoints[waypoints.Length];
pw[0].x = waypoints[0].transform.position.x ;
pw[0].y = waypoints[0].transform.position.y ;
但,因为它不会在当前上下文存在无法使用PW中更新(){
but then I cannot use pw in Update() { because it doesn't exist in current context.
和有它在上下文中我不能移动PersonalWaypoints [] PW =新PersonalWaypoints [waypoints.Length]类定义,因为waypoints.Length是在定义类未知的。
And to have it in context I cannot move PersonalWaypoints[] pw = new PersonalWaypoints[waypoints.Length]; to class definition because waypoints.Length is unknown while defining class.
推荐答案
您的问题有点的模糊的,如果你想要的 autoexpanding阵列式集合的,你必须有的两个的对象:一个用于点
You question is a bit vague, if you want autoexpanding array-like collection you have to have two objects: one for point
//TODO: think over, may be you want a struct, not class
// May be you want just a standard Point struct
public class Item {
public int x {get; set;}
public int y {get; set;}
}
和一个阵列(这是一个的索引的其实)
and one for "array" (which is an indexer in fact)
//TODO: you may want to implement IEnumerable<Item>
public class MyClass {
private List<Item> m_Items = new List<Item>();
private void Expand(int index) {
if (index < 0)
throw new ArgumentOutOfRangeException("index");
for (int i = m_Items.Count; i <= index; ++i)
m_Items.Add(new Item());
}
// indexer: mimics auto expanding array
public Item this[int index] {
get {
Expand(index);
return m_Items[index];
}
}
public int Count {
get {
return m_Items.Count;
}
}
}
...
MyClass test = new MyClass();
// test will be expanded to have 1 item: test[0]
test[0].y = 456;
// test will be expanded to have 6 items [0..5]
test[5].x = 123;
这篇关于在C#中声明的对象与X,Y paramateres的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!