问题描述:

How can we use coalescing Operator to choose method calls depending upon true or false value , as follows:

  1. Request.QueryString=="new"? NewPage() : OldPage() ;
  2. Request.QueryString=="Black"? BlackMonie(): Request.QueySTring=="White"? WhiteMonie():Tacs();

instead of the common coalescing operator call using stoage variable as follows:

string s= color=="r"? "Red" : "Green";

网友答案:

It's not overly clear from your question, but I assume that NewPage() and OldPage() are both void methods.

So, you can't use the ternary operator like you're proposing without getting into a lot of messy code that returns actions that then need to be invoked.

And there seems to be little benefit in trying to get this to work as the built in if, else keywords are pretty close to what you want.

Here are your suggested use of the ?: operator with the standard if code:

Request.QueryString == "new" ? NewPage() : OldPage();
if (Request.QueryString == "new") NewPage(); else OldPage();

That's 7 characters difference.

I'd stick with the standard if approach.

网友答案:

You could assign those methods to an appropriate delegate type, and then invoke the delegate:

var someCall = Request.QueryString=="new" ? new Action(NewPage) : new Action(OldPage);
someCall();

but you really shouldn't.

网友答案:

You just need to use a correct syntax in your ternary operator statement, like in the following sample (see MSDN ref https://msdn.microsoft.com/en-us/library/zakwfxx4%28v=vs.90%29.aspx):

string _test = (Request.QueryString=="new")? NewPage() : OldPage() ;

Hope this may help. Best regards,

相关阅读:
Top