繁体   English   中英

无法将“System.Int32”类型的 object 转换为“System.Boolean”类型。

[英]Unable to cast object of type 'System.Int32' to type 'System.Boolean'.'

当我检查 output.txt 文件时,我看到编译器没有显示 isEnable 选项,它需要是bool当我运行调试器时,我看到了这条消息

Unable to cast object of type 'System.Int32' to type 'System.Boolean'.'


korisnik.isEnabled = (bool)(result.Properties["userAccountControl"][0]);

我尝试了一些东西,但根本不起作用!

 korisnik.isEnabled = (bool)(result.Properties["userAccountControl"][0].ToString());

怎么了?

异常表示您无法将 int 转换为 boolean。 您需要确定 int 在哪些条件下应该为假或真。

例如:

  • 0 应该是假的
  • 其他一切都应该是真实的

或者

  • 1 应该是真的
  • 其他一切都应该是假的

以下是其中一种情况的示例:

// when the value is > 0, it should be true.
if(result.Properties["userAccountControl"][0] > 0)
    korisnik.isEnabled = true;
else
    korisnik.isEnabled = false;

> 0表达式将返回 boolean,因此您可以将其直接存储到isEnabled

korisnik.isEnabled = result.Properties["userAccountControl"][0] > 0;

如果result.Properties["userAccountControl"][0]存储为 object (boxed) ,则需要先将其转换为 int。

var userAccountControlValue = (int)result.Properties["userAccountControl"][0];
korisnik.isEnabled = userAccountControlValue  > 0;

暂无
暂无

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

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