C#:将对象动态添加到 List<T> 类中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16030428/
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
C#: Add objects into List<T> class dynamically
提问by king jia
I want to add all my objects into an List dynamically, without any hard coding.
我想将所有对象动态添加到 List 中,无需任何硬编码。
Code:
代码:
static void Main(string[] args)
{
Item objA = new Item();
Item objB = new Item();
int count = Item.getCount();// count = 2
List<Item> cont1 = new List<Item>();
while (count > 0)
{
for (int i = 0; i < count; i++)
{
cont1.Add();
//I missing an instance to get the objA and objB into cont1
//I dont want hard code it, e.g: cont1.Add(objA).
}
}
}
采纳答案by quetzalcoatl
Basing on your comment:
根据您的评论:
If you create 'static Item objA = new Item()' several times so that you end up with:
如果您多次创建 'static Item objA = new Item()' 以便您最终得到:
static Item objA = new Item();
static Item objB = new Item();
....
static Item objZ = new Item();
then to put them all into a list you almosthave no other way than:
然后将它们全部放入一个列表中,您几乎别无选择:
list = new List<Item>;
list.Add(objA);
list.Add(objB);
...
list.Add(objZ);
This is because you have already created the items, and already put them into several dozens of different variables and to put them into the list you simply have to tell the compiler where it should get them from. This means, that you have to tell him to get it from objA variable, and from objB variable and (...) and so on. This is because you have them in different variables.
这是因为您已经创建了这些项目,并且已经将它们放入了几十个不同的变量中,并且要将它们放入列表中,您只需告诉编译器它应该从哪里获取它们。这意味着,您必须告诉他从 objA 变量、从 objB 变量和 (...) 等中获取它。这是因为您将它们置于不同的变量中。
The point is that you should chosen wrong way at the very beginning. You should never have created "objA, objB, objC, ...., objZ" in the first place. It should be a list or array or Dictionary or whatever collection, so that you can access all items at once easily. They should not been put into separate variables.
关键是你应该在一开始就选择了错误的方式。您不应该首先创建“objA,objB,objC,....,objZ”。它应该是一个列表或数组或字典或任何集合,以便您可以轻松地一次访问所有项目。它们不应该被放入单独的变量中。
If you can, don't create that may variables. For example, use a dictionary:
如果可以,请不要创建可能的变量。例如,使用字典:
Dictionary<string, Item> items = new Dictionary<string, Item>();
items["A"] = new Item();
items["B"] = new Item();
...
items["Z"] = new Item();
now, you can an item easily:
现在,您可以轻松地创建一个项目:
items["F"].Something = 321;
items["O"].Something = 123;
and you can access all itemsalso as easily:
您也可以轻松访问所有项目:
var number = items.Values.Count;
itemList = new List<Item>( items.Values );
Of course, sometimes you just don't have such option. For example, WinForms Designer creates variables for you and if you put 100 labels onto the Form, you will almost always end up having a 100 variables (although never static).
当然,有时您只是没有这样的选择。例如,WinForms 设计器为您创建变量,如果您在表单上放置 100 个标签,您几乎总是会得到 100 个变量(尽管永远不会是静态的)。
Nevertheless, all those variables will sit in some class. If your project setup allows you to use Reflection, then you can inspect that class and obtain a list of Names/Properties, and you can read their values:
尽管如此,所有这些变量都将位于某个类中。如果您的项目设置允许您使用反射,那么您可以检查该类并获取名称/属性列表,您可以读取它们的值:
class X
{
public static Item objA = new Item();
..., objB, objC, ..... ,.....,
}
...
List<Item> items = new List<Item>();
foreach (var field in typeof(ListaUczniow).GetFields(BindingFlags.Static | BindingFlags.Public))
if (field.Name.StartsWith("obj") && field.FieldType == typeof(Item))
items.Add( (Item) field.GetValue(null) );
This may work for you, but in general, this is a very fragile approach: you have to watch out for proper BindingFlags, proper field names, proper field types, and the compiler cannot check the cast to Item automatically and even some security problems may arise if you write i.e. on Silverlight and your fields are private.
这可能对您有用,但总的来说,这是一种非常脆弱的方法:您必须注意正确的 BindingFlags、正确的字段名称、正确的字段类型,并且编译器无法自动检查对 Item 的强制转换,甚至可能会出现一些安全问题如果您在 Silverlight 上编写 ie 并且您的字段是私有的,则会出现这种情况。
回答by Jan Van Herck
int count = Item.getCount();// count = 2
looks to me as if your Item class increases a counter "under the hood" when the constructor is called and you want to access each instance of this class in your loop?
在我看来,当构造函数被调用并且您想访问循环中此类的每个实例时,您的 Item 类好像在“幕后”增加了一个计数器?
If so, your best bet seems to add the List directly as a (private) static property to the Item class itself and have the constructor do Add(this) to this list. Exposing it could then be done through a static ReadOnlyCollection<Item>collection.
如果是这样,最好的办法似乎是将 List 作为(私有)静态属性直接添加到 Item 类本身,并让构造函数将 Add(this) 添加到此列表。然后可以通过静态ReadOnlyCollection<Item>集合来公开它。

