简体   繁体   中英

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();

I've put that list into a combo box to be displayed to the user in the drop-down menu. I'm trying to create an instance of the selected item of the combo box which is a subclass of a class called BotPlayer and is meant to make use of a method called "Move" which is present in the class and all its subclasses. I'm also trying to pass that instance into a BotPlayer variable called Bot. I've tried the different ways of using Activator.CreateInstance but it doesn't seem to work for me or I don't understand it enough to implement it into my own program. This was the furthest I was able to get

Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem);

When I run my program it gives me this error: "System.MissingMethodException: 'No parameterless constructor defined for this object.'"

This is the code for the combo box which exists in the 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;

This is the code for the combo box which exists in the normal cs file

        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");
        }

This is the BotPlayer Constructor

       public BotPlayer(GameBoard board, SquareValues type)
    {
        Type = type;
        Board = board;
       // Difficuty = difficulty;
    }

This is the constructor for all its subclasses

    public BotPlayer1(GameBoard board, SquareValues type) : base(board, type)
    {
        Board = board;
        Type = type;
        BotName = "Level 1";          
    }

The only difference between the subclasses is the number at the end of BotPlayer and the bot name which is equivalent to that number with the word "Level" behind it

Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem,Board,BotType);

I found that all I needed to do was pass in parameters into the Activator.CreateInstance.

Thanks to @elgonzo and @Neil for helping me realize this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM