简体   繁体   English

从“字符串”转换为“ GSMModemTypeConstants”时发生Convert.ChangeType错误

[英]Error of Convert.ChangeType in conversion from “string” to “GSMModemTypeConstants”

comboBox2.DataSource = Enum.GetValues(typeof(GSMModemTypeConstants));
GSMModemTypeConstants s_type = (GSMModemTypeConstants)Convert.ChangeType(
    comboBox2.Text, typeof(GSMModemTypeConstants));

In the first line the user select the type of his modem from a comboBox which gets the list of the modems available from the Enum GSMModemTypeConstants. 在第一行中,用户从comboBox中选择其调制解调器的类型,该列表可从Enum GSMModemTypeConstants获取可用的调制解调器列表。 In the second line I want to pass the selected modem type to s_type which will later be used by the method that actually sends the SMS. 在第二行中,我想将选定的调制解调器类型传递给s_type,稍后将由实际发送SMS的方法使用。

When I manually set the s_type everything works perfect for example: 当我手动设置s_type时,一切都可以正常运行,例如:

GSMModemTypeConstants s_type = GSMModemTypeConstants.gsmModemSonyEricsson;
// OR
GSMModemTypeConstants s_type = GSMModemTypeConstants.gsmModemNokia;

But when I try to retrieve the choice from the comboBox and set the s_type like I do in the second line the conversion gives me an error which I can't understand. 但是,当我尝试从comboBox检索选择并像第二行一样设置s_type ,转换给了我一个我无法理解的错误。

错误

Am I handling the Convert.ChangeType method wrong? 我处理Convert.ChangeType方法错误吗? If it's not my fault then is there any other way to convert a type from string to something else, other than Convert.ChangeType ? 如果不是我的错,那么除了Convert.ChangeType之外,还有其他方法可以将类型从字符串转换为其他类型吗?


Solution I still don't have the required reputation to answer it below, so here is the code... 解决方案我仍然没有所需的声誉来回答以下问题,因此这里是代码...

GSMModemTypeConstants s_type = (GSMModemTypeConstants)System.Enum.Parse(
    typeof(GSMModemTypeConstants), comboBox2.Text);`

If comboBox2.Text has a number (integer) then you should first convert that value to int and then cast it to GSMModemTypeConstants , eg: 如果comboBox2.Text具有数字(整数),则应首先将该值转换为int ,然后将其GSMModemTypeConstants转换为GSMModemTypeConstants ,例如:

int modemType = int.Parse(comboBox2.Text));
GSMModemTypeConstants s_type = (GSMModemTypeConstants)modemType;

Or, convert comboBox2.SelectedItem to your enum. 或者,将comboBox2.SelectedItem转换为您的枚举。

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

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