从对象列表中获取并添加 Mname 类型的所有属性,并将它们动态添加到下拉列表中

Get and add all properties of type Mname from a list of objects and add them dynamically too a drop down

好的,我有一个名为怪物的对象类型和所有怪物的列表 我需要从名为 MName 的 属性 中获取所有字符串,并将每个字符串添加到下拉文本框。

这是目前的 class。(对不起,我真的是编码新手。)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication1
{
    public class Monsters
    {
        public string MonsterName { get; set; }
        public int MonsterAttackMin { get; set; }
        public int MonsterAttackMax { get; set; }
        public Monsters (string MName, int MAttackMin, int MAttackMax)
{
        MonsterName = MName;
        MonsterAttackMin = MAttackMin;
        MonsterAttackMax = MAttackMax;
}


        List<Monsters> monstersObjectList = new List<Monsters>
        {
             new Monsters("Blob",0,5){},
             new Monsters("Wolf",0,5){},

        };


        //foreach (List<Monsters>//**DontKnowPastHere** M in monsterObjectList)


       // Monsters Blob = new Monsters("Blob",0,5); 
}

}

foreach 循环中,循环变量的类型是集合中项目的类型,因此您需要:

foreach (Monster m in monsterObjectList)
    ddlMonsters.Items.Add(new ListItem(m.MonsterName));

您也可以绑定列表作为数据源:

ddlMonsters.DataSource = monsterObjectList;
ddlMonsters.DataTextField = "MonsterName"; 
ddlMonsters.DataBind();