![](/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.