I tried the following:
(id == title) | (id.开发者_JS百科IsNullOrEmpty) ? "class='enabled'" : ""
But it gives a message saying "Error 22 Operator '|' cannot be applied to operands of type 'bool' and 'method group'
Can anyone tell me what's wrong. Both id and title are strings.
Looks like you're using |
instead of ||
and I'm not sure if you have IsNullOrEmpty
defined as an extension method but you're mussing the ()
to invoke it. That or just call String.IsNullOrEmpty
directly.
Try the following
(id == title || String.IsNullOrEmpty(id)) ? "class='enabled'" : ""
I'm not a C# developer, but try || instead of |. The difference between the operators is explained here http://msdn.microsoft.com/en-us/library/aa691310(v=vs.71).aspx.
Also, is ==
the correct way to compare strings in C#? In Java you need to use .equals()
.
(UPDATED: apparently | is nothing to do with the bitwise operator).
You're using bitwise OR (|). You need logical OR (||).
if ( id == null || id == title )
{
// id is null or id equals title.
}
Note that the equality operator (==) is case sensitive. To do a case insensitive comparison use the static method String.Compare.
if ( id == null || String.Compare( id, title, true ) == 0 )
{
// id is null or id equals title (ignoring case).
}
Try it like this instead:
(id == title) || id.IsNullOrEmpty() ? "class='enabled'" : ""
If you want to test for "Is this string null (or empty) or equal to another string", then just say that:
if (string.IsNullOrEmpty(id) || id.Equals(title))
{
// Code here
}
As a ternary operation:
var result = (string.IsNullOrEmpty(id) || id.Equals(title) ? "class='enabled'" : "";
精彩评论