问题
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