简体   繁体   English

如何在运行时转换为从String(=类的名称)获得的类型?

[英]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. 我需要获取在运行时强制转换的类型,在这种特殊情况下,我不能使用通用的“ T”类或方法。

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. 尽管如果您有一种在运行时更改T泛型类型的方法(而无需再次调用类或方法),那也会有所帮助。

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. 我有一个列表comboList,我的GUI可以在运行时添加新的ComboBox,这些将自动放入comboList。 Now there are database tables for each of those ComboBoxes in comboList. 现在,comboList中的每个组合框都有数据库表。 I added the name of each of the database classes in the .Tag field of each ComboBox 我在每个ComboBox的.Tag字段中添加了每个数据库类的名称。

(example: combobox_users.Tag = "users_databaseClass") (示例: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. 现在在运行时,例如,我需要转换为users_databaseClass的类型,但是在我看来这是不可能的。 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") ). 要使用古怪类型的属性和方法,您需要对该类型的引用(例如Type.GetType("string_name_of_type") ),并且需要一些非常酷的反射(例如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 参见http://msdn.microsoft.com/zh-cn/library/system.type.getmethod(v=vs.71).aspx

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

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