简体   繁体   English

如何实现类的字符串名称与类本身的一致性?

[英]How to implement accordance between string name of the class and class itself?

I have a comboBox at my Form.我的表单中有一个组合comboBox When i'm pressing it, list of the names of the classes popped up.当我按下它时,弹出类的名称列表。 And when i'm choosing some name of the class there, i want to create object of that class and then work with it.当我在那里选择某个类的名称时,我想创建该类的对象,然后使用它。 All my classes have a common parent, so i used this code to get all my sub classes:我所有的类都有一个共同的父类,所以我使用这个代码来获取我所有的子类:

var subclassTypes = Assembly
                    .GetAssembly(typeof(ParentClass))
                    .GetTypes()
                    .Where(t => t.IsSubclassOf(typeof(ParentClass)));

So after that i just added this to ComboBox , and its's work okay, it's showing all the classes i need in string.所以在那之后,我只是将它添加到ComboBox ,它的工作正常,它以字符串形式显示了我需要的所有类。 But how can i make an accordance between string name of the class and class itself?但是我怎样才能在类的字符串名称和类本身之间建立一致呢? How can i store that accordance and how can i make it?我如何存储该符合性以及如何实现?

You already have all the Type s of your classes.您已经拥有类的所有Type Creating a new instance of one of them is then just something like (assuming comboboxSelection as the selected class name):创建其中一个的新实例就像这样(假设comboboxSelection选择作为选定的类名):

var classType = subclassTypes.First(t => t.Name == comboBoxSelection);
var classInstance = Activator.CreateInstance(classType);

Note that in the example classInstance is of type object .请注意,示例中的classInstanceobject类型。 You can easily cast it to the common type though:不过,您可以轻松地将其转换为普通类型:

var classInstance = (ParentClass)Activator.CreateInstance(classType);

Note that for Activator.CreateInstance to work, the classes need to have a constructor without parameters.请注意,要使Activator.CreateInstance工作,类需要有一个不带参数的构造函数。

You could store the types directly in the combobox and use the SelectedItem property to retrieve them in the SelectedIndexChanged event:您可以将类型直接存储在组合框中,并使用SelectedItem属性在SelectedIndexChanged事件中检索它们:

List<Type> subclassTypes = Assembly
        .GetAssembly(typeof(ParentClass))
        .GetTypes()
        .Where(t => t.IsSubclassOf(typeof(ParentClass))).ToList();


comboBoxTypes.DataSource = subclassTypes;
comboBoxTypes.DisplayMember = "Name";

Using the Activator.CreateInstance method you can create an object of that type.使用Activator.CreateInstance方法,您可以创建该类型的对象。

private void ComboBoxTypes_SelectedIndexChanged(object sender, EventArgs e)
{
    Type itemType = comboBoxTypes.SelectedItem as Type;

    ParentClass item = (ParentClass)Activator.CreateInstance(itemType);
}

Disclaimer: this solution is for a parameterless constructor!免责声明:此解决方案适用于无参数构造函数!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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