如何在c#中创建多个对象并枚举它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1235477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create multiple objects and enumerate them in c#
提问by
my problem is as follows:
我的问题如下:
Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object. The new objects name should contain a counting number starting from 1.
我正在构建一个控制台应用程序,它询问用户应该创建的对象数量以及必须为每个对象分配的 4 个变量。新对象名称应包含从 1 开始的计数。
How would you solve this? Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go?
你会如何解决这个问题?我正在考虑一个类,但我不确定如何在运行时从用户输入创建对象。循环是最好的方法吗?
What kind of class, struct, list, array .... would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program.
你会推荐什么样的类、结构、列表、数组……。对象中的变量总是相同的类型,但我需要正确命名它们,以便我可以有效地编写方法来在程序的后期阶段对它们执行操作。
Im just learning the language and I would be very thankful for a advice on how to approach my problem.
我只是在学习这门语言,我将非常感谢您提供有关如何解决我的问题的建议。
采纳答案by Thorarin
If I understand your problem correctly:
如果我正确理解您的问题:
class MyClass
{
public int ObjectNumber { get; set; }
public string SomeVariable { get; set; }
public string AnotherVariable { get; set; }
}
// You should use keyboard input value for this
int objectsToCreate = 10;
// Create an array to hold all your objects
MyClass[] myObjects = new MyClass[objectsToCreate];
for (int i = 0; i < objectsToCreate; i++)
{
// Instantiate a new object, set it's number and
// some other properties
myObjects[i] = new MyClass()
{
ObjectNumber = i + 1,
SomeVariable = "SomeValue",
AnotherVariable = "AnotherValue"
};
}
This doesn't quite do what you described. Add in keyboard input and stuff :) Most of this code needs to be in some kind of Main
method to actually run, etc.
这并不完全符合您的描述。添加键盘输入和其他东西:) 大部分代码需要采用某种Main
方法才能实际运行,等等。
In this case, I've chosen a class
to hold your 4 variables. I have only implemented 3 though, and I've implemented them as properties, rather than fields. I'm not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don't want to be the one to teach you bad habits. See auto-implemented properties.
在这种情况下,我选择了一个class
来保存您的 4 个变量。不过我只实现了 3 个,并且我已经将它们实现为属性,而不是字段。我不确定这对您的作业是否必要,但通常来说,没有可公开访问的字段是一个好习惯,我不想成为教您坏习惯的人。请参阅自动实现的属性。
You mentioned a struct
, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet.
您提到了 a struct
,这也是一个选项,具体取决于您要存储的内容。不过,一般来说,上课会更安全。
A loop would indeed be the way to go to initialize your objects. In this case, a for
loop is most practical. It starts counting at 0
, because we're putting the objects in an array, and array indexes in C# always start at 0
. This means you have to use i + 1
to assign to the object number, or the objects would be numbered 0 - 9, just like their indexes in the array.
循环确实是初始化对象的方法。在这种情况下,for
循环是最实用的。它从 开始计数0
,因为我们将对象放入数组中,而 C# 中的数组索引总是从 开始0
。这意味着您必须使用i + 1
分配给对象编号,否则对象将编号为 0 - 9,就像它们在数组中的索引一样。
I'm initializing the objects using object initializer syntax, which is new in C# 3.0. The old fashioned way would be to assign them one by one:
我正在使用对象初始值设定项语法初始化对象,这是 C# 3.0 中的新功能。老式的方法是将它们一一分配:
myObjects[i] = new MyClass();
myObjects[i].ObjectNumber = i + 1;
myObjects[i].SomeVariable = "SomeValue";
Alternatively, you could define a constructorfor MyClass
that takes 3 parameters.
或者,你可以定义一个构造函数用于MyClass
这需要3个参数。
One last thing: some people here posted answers which use a generic List(List<MyClass>
) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we'll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later.
最后一件事:这里的一些人发布了使用通用 List( List<MyClass>
) 而不是数组的答案。这将工作正常,但在我的示例中,我选择使用您可以使用的最基本的形式。与数组不同,列表没有固定大小(注意我是如何初始化数组的)。如果您想稍后添加更多项目,或者如果您事先不知道需要存储多少项目,则列表非常有用。然而,在这种情况下,我们有键盘输入,所以我们确切地知道我们将拥有多少项目。因此:数组。它会隐含地告诉正在阅读您的代码的人,您不打算稍后添加更多项目。
I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes :P
我希望这回答了一些问题,并提出了一些新问题。看看兔子洞有多深:P
回答by driis
Use a list or an array. List example:
使用列表或数组。列表示例:
int numberOfObjects = 3;
List<YourType> listOfObjects = new List<YourType>();
for(int i = 0 ; i < numberOfObjects ; i++ )
{
// Get input and create object ....
// Then add to your list
listOfObjects.Add(element);
}
Here, listOfObjects is a Generic list that can contain a variable number of objects of the type YourType. The list will automatically resize so it can hold the number of objects you add to it. Hope this helps.
这里,listOfObjects 是一个通用列表,它可以包含可变数量的 YourType 类型的对象。该列表将自动调整大小,以便它可以容纳您添加到其中的对象数量。希望这可以帮助。
回答by Anzurio
If I understood what you are asking you could probably do something like this:
如果我明白你在问什么,你可能会做这样的事情:
class Foo
{
private static int count;
public string name;
public Foo(...){
name = ++count + "";
}
}
回答by Randolpho
I'm guessing what you're trying to do here, but this is a stab in the dark. The problem I'm having is dealing with the whole "the new objects name should contain a counting number starting from 1" thing. Anyway, here's my attempt:
我猜你想在这里做什么,但这是在黑暗中刺伤。我遇到的问题是处理整个“新对象名称应包含从 1 开始的计数”的问题。无论如何,这是我的尝试:
public class UserInstantiatedClass
{
public int UserSetField1;
public int UserSetField2;
public int UserSetField3;
public int UserSetField4;
public string UserSpecifiedClassName;
}
public static class MyProgram
{
public static void Main(string [] args)
{
// gather user input, place into variables named
// numInstances, className, field1, field2, field3, field4
List<UserInstantiatedClass> instances = new List< UserInstantiatedClass>();
UserInstantiatedClass current = null;
for(int i=1; i<=numInstances; i++)
{
current = new UserInstantiatedClass();
current.UserSpecifiedClassName = className + i.ToString(); // adds the number 1, 2, 3, etc. to the class name specified
current.UserSetField1 = field1;
current.UserSetField2 = field2;
current.UserSetField3 = field3;
current.UserSetField4 = field4;
instances.Add(current);
}
// after this loop, the instances list contains the number of instances of the class UserInstantiatedClass specified by the numInstances variable.
}
}