Sök…


Syntax

  • kontrollerad (a + b) // kontrollerad uttryck
  • unchecked (a + b) // unchecked expression
  • kontrollerad {c = a + b; c + = 5; } // kontrollerat block
  • avmarkerad {c = a + b; c + = 5; } // avmarkerat block

Kontrollerad och avmarkerad

C # -satser körs i antingen kontrollerat eller okontrollerat sammanhang. I ett kontrollerat sammanhang ger aritmetiskt översvämning ett undantag. I okontrollerat sammanhang ignoreras aritmetiskt överflöde och resultatet trunkeras.

short m = 32767;   
short n = 32767;
int result1 =  checked((short)(m + n));   //will throw an OverflowException
int result2 =  unchecked((short)(m + n)); // will return -2

Om ingen av dessa anges kommer standardkontext att förlita sig på andra faktorer, t.ex. kompilatoralternativ.

Kontrollerad och avmarkerad som omfattning

Nyckelorden kan också skapa scopes för att (av) kontrollera flera operationer.

short m = 32767;
short n = 32767;
checked
{
    int result1 = (short)(m + n); //will throw an OverflowException
}
unchecked
{
    int result2 = (short)(m + n); // will return -2
}


Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow