?: operator - C# reference | Microsoft Docs

文章推薦指數: 80 %
投票人數:10人

Learn about the C# ternary conditional operator that returns the result of one of the two expressions based on a Boolean expression's ... Skiptomaincontent Thisbrowserisnolongersupported. UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport. DownloadMicrosoftEdge Moreinfo Tableofcontents Exitfocusmode ReadinEnglish Save Tableofcontents ReadinEnglish Save Feedback Edit Twitter LinkedIn Facebook Email Tableofcontents ?:operator(C#reference) Article 06/18/2022 3minutestoread 12contributors Inthisarticle Theconditionaloperator?:,alsoknownastheternaryconditionaloperator,evaluatesaBooleanexpressionandreturnstheresultofoneofthetwoexpressions,dependingonwhethertheBooleanexpressionevaluatestotrueorfalse,asthefollowingexampleshows: stringGetWeatherDisplay(doubletempInCelsius)=>tempInCelsius<20.0?"Cold.":"Perfect!"; Console.WriteLine(GetWeatherDisplay(15));//output:Cold. Console.WriteLine(GetWeatherDisplay(27));//output:Perfect! Astheprecedingexampleshows,thesyntaxfortheconditionaloperatorisasfollows: condition?consequent:alternative Theconditionexpressionmustevaluatetotrueorfalse.Ifconditionevaluatestotrue,theconsequentexpressionisevaluated,anditsresultbecomestheresultoftheoperation.Ifconditionevaluatestofalse,thealternativeexpressionisevaluated,anditsresultbecomestheresultoftheoperation.Onlyconsequentoralternativeisevaluated. BeginningwithC#9.0,conditionalexpressionsaretarget-typed.Thatis,ifatargettypeofaconditionalexpressionisknown,thetypesofconsequentandalternativemustbeimplicitlyconvertibletothetargettype,asthefollowingexampleshows: varrand=newRandom(); varcondition=rand.NextDouble()>0.5; int?x=condition?12:null; IEnumerablexs=xisnull?newList(){0,1}:newint[]{2,3}; Ifatargettypeofaconditionalexpressionisunknown(forexample,whenyouusethevarkeyword)orinC#8.0andearlier,thetypeofconsequentandalternativemustbethesameortheremustbeanimplicitconversionfromonetypetotheother: varrand=newRandom(); varcondition=rand.NextDouble()>0.5; varx=condition?12:(int?)null; Theconditionaloperatorisright-associative,thatis,anexpressionoftheform a?b:c?d:e isevaluatedas a?b:(c?d:e) Tip Youcanusethefollowingmnemonicdevicetorememberhowtheconditionaloperatorisevaluated: isthisconditiontrue?yes:no Conditionalrefexpression BeginningwithC#7.2,areflocalorrefreadonlylocalvariablecanbeassignedconditionallywithaconditionalrefexpression.Youcanalsouseaconditionalrefexpressionasareferencereturnvalueorasarefmethodargument. Thesyntaxforaconditionalrefexpressionisasfollows: condition?refconsequent:refalternative Liketheoriginalconditionaloperator,aconditionalrefexpressionevaluatesonlyoneofthetwoexpressions:eitherconsequentoralternative. Inthecaseofaconditionalrefexpression,thetypeofconsequentandalternativemustbethesame.Conditionalrefexpressionsarenottarget-typed. Thefollowingexampledemonstratestheusageofaconditionalrefexpression: varsmallArray=newint[]{1,2,3,4,5}; varlargeArray=newint[]{10,20,30,40,50}; intindex=7; refintrefValue=ref((index<5)?refsmallArray[index]:reflargeArray[index-5]); refValue=0; index=2; ((index<5)?refsmallArray[index]:reflargeArray[index-5])=100; Console.WriteLine(string.Join("",smallArray)); Console.WriteLine(string.Join("",largeArray)); //Output: //1210045 //102004050 Conditionaloperatorandanifstatement Useoftheconditionaloperatorinsteadofanifstatementmightresultinmoreconcisecodeincaseswhenyouneedconditionallytocomputeavalue.Thefollowingexampledemonstratestwowaystoclassifyanintegerasnegativeornonnegative: intinput=newRandom().Next(-5,5); stringclassify; if(input>=0) { classify="nonnegative"; } else { classify="negative"; } classify=(input>=0)?"nonnegative":"negative"; Operatoroverloadability Auser-definedtypecannotoverloadtheconditionaloperator. C#languagespecification Formoreinformation,seetheConditionaloperatorsectionoftheC#languagespecification. FormoreinformationaboutfeaturesaddedinC#7.2andlater,seethefollowingfeatureproposalnotes: Conditionalrefexpressions(C#7.2) Target-typedconditionalexpression(C#9.0) Seealso Simplifyconditionalexpression(styleruleIDE0075) C#reference C#operatorsandexpressions ifstatement ?.and?[]operators ??and??=operators refkeyword Feedback Submitandviewfeedbackfor Thisproduct Thispage Viewallpagefeedback Inthisarticle



請為這篇文章評分?