对象数组问题

rog_rickert

新成员
已加入
2020年12月17日
留言内容
4
编程经验
Beginner
你好,

我对C#和自学还很陌生。我已经四处搜寻,但没有找到答案,所以我想知道是否有人可以让我知道这是否可行。

I need to have 一个对象的多个实例 that can be accessed by multiple forms. I know I can do this with static class or a singleton. 什么 I need to know is if it possible to have an array of these objects so that I can reference them by index.

像这样的东西:
(伪代码)

公共类事物{

public int var1;
public int var2;

}

然后使用创建

事物[]事物=新事物[4];


并像这样引用它们:


something [0] .var1 =某些东西;
something [0] .var2 =某些东西;


something [1] .var1 =某物;
something [1] .var2 =某物;

等等


任何指向我正确方向的信息都将受到赞赏。
 

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,465
位置
悉尼,澳大利亚
编程经验
10+
首先,没有这样的事情"一个对象的多个实例"。您可以具有一个类型的多个实例,并且每个实例都是一个对象。考虑一下现实世界中的对象如何工作。编程对象也是如此,因为OOP基于真实世界的对象行为。在现实世界"table"是一种东西,对吗?"Table" is basically a set of attributes that describes something that is a 表. If you go to a furniture store and buy a 表 and bring it home, you now have a 表 object. You can't have multiple instances of that object. It's one object. You can get other 表s, so other objects of the same type that may or may not have all the same attributes, but they are all distinct objects. If you always think about how objects work in the real world while programming in an OO language, things will likely go smoother. There are some exceptions but, generally, programming objects will work the same way.
 

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,465
位置
悉尼,澳大利亚
编程经验
10+
当然,关于您的问题。数组是一个像其他对象一样的对象。如果可以将对象放置在某处,则可以在其中放置数组,因为数组是对象。

When dealing with arrays, I like to use egg cartons as an analogy. Just like having an egg carton provides multiple places where you can put an egg but it doesn't mean that you have any eggs, so having an array provides places where you can place other objects but it doesn't mean that you have those objects. If you create a Thing array with four elements then you have places to store four Thing objects but you still have to create those objects and place them there. Think of each array element as a variable. Just as a variable is null by default and requires you to create an object and assign it to the variable, so each array element is null by default and requires you to create an object and assign it to the element.

Unless you know for a fact that you will always have exactly four objects to store in the array, you probably ought to use a List<Thing> instead, which is basically dynamic array. It works just like an array in many ways, allowing you to index it to get or set an item. Unlike an array though, it will grow and shrink automatically as you call Add and Remove.
 
最佳 底部