[英]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));
在第一行中,用户从comboBox中选择其调制解调器的类型,该列表可从Enum GSMModemTypeConstants获取可用的调制解调器列表。 在第二行中,我想将选定的调制解调器类型传递给s_type,稍后将由实际发送SMS的方法使用。
当我手动设置s_type时,一切都可以正常运行,例如:
GSMModemTypeConstants s_type = GSMModemTypeConstants.gsmModemSonyEricsson;
// OR
GSMModemTypeConstants s_type = GSMModemTypeConstants.gsmModemNokia;
但是,当我尝试从comboBox
检索选择并像第二行一样设置s_type
,转换给了我一个我无法理解的错误。
我处理Convert.ChangeType
方法错误吗? 如果不是我的错,那么除了Convert.ChangeType
之外,还有其他方法可以将类型从字符串转换为其他类型吗?
解决方案我仍然没有所需的声誉来回答以下问题,因此这里是代码...
GSMModemTypeConstants s_type = (GSMModemTypeConstants)System.Enum.Parse(
typeof(GSMModemTypeConstants), comboBox2.Text);`
如果comboBox2.Text
具有数字(整数),则应首先将该值转换为int
,然后将其GSMModemTypeConstants
转换为GSMModemTypeConstants
,例如:
int modemType = int.Parse(comboBox2.Text));
GSMModemTypeConstants s_type = (GSMModemTypeConstants)modemType;
或者,将comboBox2.SelectedItem
转换为您的枚举。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.