Ternary operator on System::Boolean variable

二次信任 提交于 2019-12-13 03:28:02

问题


How to use ternary operator with System::Boolean? This sample code always returns true:

bool Test(Boolean^ value)
{
  return value ? true : false;
}

回答1:


Your usage of System::Boolean is wrong in the first place and it has nothing to do with ternary operator. Never pass a value types as reference.

Regadless of unnecessary penalities, the code in your answer will work but not in C#. The compiler will complain when you want to call bool Test(Boolean^ value) function. Because there is no concept of referenced value type in C#.




回答2:


Answering my own premature question, this code works:

bool Test(Boolean^ value)
{
  return (bool)value ? true : false;
}

EDIT: better yet (and following Hans' and Matt's advice) this code works better:

bool Test(Boolean value)
{
  return value ? true : false;
}

Or, because Boolean and bool are convertible this is also good code, which relies on automatic conversion that happens elsewhere. Example has very little sense except for showing the ternary operator:

bool Test(bool value)
{
  return value ? true : false;
}


来源:https://stackoverflow.com/questions/8744929/ternary-operator-on-systemboolean-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!