字符串比较无法正常工作?
我正在使用这个 library 来挂钩键,并且在比较时遇到一些问题e.KeyCode.ToString() 具有相同的字符串。
我有一个相当于
Keys.Oemtilde
-> 字符串的变量 Program.KeyboardTradeHotkey = "Oemtilde";
我将其保留在字符串中,因为我从 xml 文件中读取该字符串,而且我似乎无法找到任何方法将字符串转换为 Keys
。
如果我这样使用它:
if (e.KeyCode.Equals(Keys.Oemtilde)) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
它工作正常并且: Logging.AddToLog("[Keyboard][Check] " + e.KeyCode); 被执行。
如果我使用它:
if (e.KeyCode.ToString() == Program.KeyboardTradeHotkey) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
它执行 else 子句。即使字符串(e.KeyCode.ToString() 和 Program.KeyboardTradeHotkey 相同,在这种情况下 String Compare 似乎也不起作用。
这可能是什么原因?
I'm using this library to hook keys and I have some problems with comparing e.KeyCode.ToString() with same string.
I have variable which is string equivalent of
Keys.Oemtilde
->Program.KeyboardTradeHotkey = "Oemtilde";
I keep it in string because I read that string from xml file and I can't seem to get any way to convert string to Keys
.
If i use it this way:
if (e.KeyCode.Equals(Keys.Oemtilde)) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It works fine and: Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
is executed.
If i use it:
if (e.KeyCode.ToString() == Program.KeyboardTradeHotkey) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It executes else clause. It seems like String Compare doesn't really works in this case even thou both string (e.KeyCode.ToString() and Program.KeyboardTradeHotkey are the same.
What can be the reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一个更改是使用 string.Equals 函数来比较字符串
another change make use of string.Equals function to compare string
我认为这是因为 KeyCode.ToString() 没有返回您期望的结果。查看手表中的视图。
I think it is because KeyCode.ToString() doesn't return what you expect it to return. Look at the view in a Watch.
无需查看您正在使用的库,第一个(工作)代码示例看起来像是在比较枚举值,因此它返回一个数字而不是字符串。
Without having to look at the library that you are using the first (working) code sample looks like it is comparing enum values, so it is returning a number instead of a string.
== 和 .Equals() 之间的差异是因为引用类型和值类型之间的差异。此链接提供了不同结果的示例:== 和 .Equals() 的比较
我也同意 pranay_stacker 的观点。
The difference between == and .Equals() is because of the differences between reference types and value types. This link gives examples of the different results: Comparison of == and .Equals()
I also agree with pranay_stacker.