![](/img/trans.png)
[英]How to Create combo box to auto fill while user type the spelings inside the combo Box in c#
[英]C# How to create an instance from a given reflection Type from a list of Type in a Combo-Box
List<Type> BotNames = typeof(BotPlayer).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(BotPlayer))).ToList();
我已将该列表放入组合框,以在下拉菜单中向用户显示。 我正在尝试创建组合框所选项目的实例,该实例是称为BotPlayer的类的子类,并且打算利用该类及其所有子类中存在的名为“ Move”的方法。 我还试图将该实例传递到名为Bot的BotPlayer变量中。 我尝试了使用Activator.CreateInstance的不同方式,但是它似乎对我不起作用,或者我对它的理解不足以将其实现到自己的程序中。 这是我能得到的最远的
Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem);
当我运行程序时,它给了我这个错误:“ System.MissingMethodException:'没有为此对象定义无参数构造函数。'”
这是Designer.cs中存在的组合框的代码
this.Difficulty.FormattingEnabled = true;
this.Difficulty.Items.AddRange(BotNames.ToArray());
this.Difficulty.Location = new System.Drawing.Point(205, 181);
this.Difficulty.Name = "Difficulty";
this.Difficulty.Size = new System.Drawing.Size(137, 21);
this.Difficulty.TabIndex = 3;
这是普通cs文件中存在的组合框的代码
if (Difficulty.SelectedItem != null)
{
Bot = (BotPlayer)Difficulty.SelectedItem; //This is called casting
Bot.Type = BotType;
//Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem);
//Bot = (BotPlayer)Activator.CreateInstance("MyAssembly", "BotPlayer");
}
这是BotPlayer构造函数
public BotPlayer(GameBoard board, SquareValues type)
{
Type = type;
Board = board;
// Difficuty = difficulty;
}
这是其所有子类的构造函数
public BotPlayer1(GameBoard board, SquareValues type) : base(board, type)
{
Board = board;
Type = type;
BotName = "Level 1";
}
子类之间的唯一区别是BotPlayer末尾的数字和bot名称,该名称与该名称后面带有“ Level”字样的数字等效
Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem,Board,BotType);
我发现我需要做的就是将参数传递到Activator.CreateInstance中。
感谢@elgonzo和@Neil帮助我实现了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.