我不确定我在这里做错了什么。我有一个类来创建一些reg键值,我继续得到类型转换错误。我传了钥匙的名字。键的值是int。哪个也应该是返回值。
我继续收到此错误
无法将类型'string'隐式转换为int
在以下位置:
rValue = (string)myKey.GetValue("DebugLog");
&set { DebugLog = getDebugLog(value);}
请注意c#
private int DebugLog;
private int getDebugLog(String name)
{
int rValue;
myKey = Registry.LocalMachine.OpenSubKey(regKey + name, false);
rValue = (string)myKey.GetValue("DebugLog");
return rValue;
}
public int debugLog
{
get { return DebugLog; }
set { DebugLog = getDebugLog(value);}
}
答案 0 :(得分:7)
注册表在此处无关紧要 - 您将值转换为string
,然后尝试将该表达式分配给int
变量。就像这样:
object x = "hello";
int y = (string) x;
那永远无法奏效。如果要将字符串转换为整数,则需要对其进行解析,例如使用int.Parse
或int.TryParse
。
如果注册表中的值实际上是一个整数,只需将其强制转换为该值。
答案 1 :(得分:2)
rValue = Convert.ToInt32(myKey.GetValue("DebugLog"));
答案 2 :(得分:0)
您将rValue声明为int,但将其设置为字符串。试试这个:
rvalue = Int32.Parse((string)myKey.GetValue("DebugLog"));
答案 3 :(得分:-1)
什么是“DebugLog”?值集了吗?
private int getDebugLog(String name)
{
int rValue;
myKey = Registry.LocalMachine.OpenSubKey(regKey + name, false);
object o = myKey.GetValue("DebugLog");
if (o != null) {
rValue = o.ToString();
if (!String.IsNullOrEmpty(rValue)) {
return Convert.ToInt32(Convert.ToDecimal(rValue));
}
}
return null;
}