简体   繁体   中英

How do I cast into a type that I got from a String(=the name of the class) at runtime?

I need to cast like this:

/* Cast Brakets */                    
(Type.FromString(mystring))myObject.doSomething();

I need to get the type that I cast at runtime, in this particular case I can't use a generic "T" class or method.

Although if you had a way of changing the T-generic Type at runtime (without calling a class or method again) that would also help.

Here is a more specific version of my problem:

I have a List comboList and my GUI can add new ComboBoxes at runtime, these will automatically be put into comboList. Now there are database tables for each of those ComboBoxes in comboList. I added the name of each of the database classes in the .Tag field of each ComboBox

(example: combobox_users.Tag = "users_databaseClass")

Now at runtime I need to cast into the type of users_databaseClass for example, but it appears to me that this is impossible. It appears that this is simply not possible to put a Type into cast-brackets at runtime to actually cast that type.

Help would be greatly appreciated, I've been trying for days.

To use the properties and methods of a wacky type, you'll need a reference to that type (eg Type.GetType("string_name_of_type") ) and you'll need some pretty cool reflection (eg theType.GetMethod("method_name") ). Your performance won't be great. See http://msdn.microsoft.com/en-us/library/system.type.getmethod(v=vs.71).aspx

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