C# 확인 및 확인되지 않은 사용법

黄舟
풀어 주다: 2016-12-28 10:47:53
원래의
1725명이 탐색했습니다.

checked 키워드는 정수 산술 연산 및 변환에 대한 오버플로 검사를 명시적으로 활성화하는 데 사용됩니다.

기본적으로 표현식에 상수 값만 포함된 경우 결과 값이 대상 유형의 범위를 벗어나면 컴파일러 오류가 발생합니다. 표현식에 상수가 아닌 값이 하나 이상 포함되어 있으면 컴파일러는 오버플로를 감지하지 않습니다. 다음 예에서는 i2에 할당된 표현식을 평가해도 컴파일러 오류가 발생하지 않습니다.

// The following example causes compiler error CS0220 because 2147483647 
// is the maximum value for integers.  
//int i1 = 2147483647 + 10; 
  
// The following example, which includes variable ten, does not cause 
// a compiler error. 
int ten = 10; 
int i2 = 2147483647 + ten; 
  
// By default, the overflow in the previous statement also does 
// not cause a run-time exception. The following line displays  
// -2,147,483,639 as the sum of 2,147,483,647 and 10. 
Console.WriteLine(i2);
로그인 후 복사

기본적으로 이러한 상수가 아닌 표현식은 런타임 시 오버플로를 확인하지 않으며 이러한 표현식은 오버플로 예외를 발생시키지 않습니다. 위의 예에서는 -2,147,483,639가 두 양의 정수의 합으로 표시됩니다.

컴파일러 옵션, 환경 구성 또는 selected 키워드를 사용하여 오버플로 검사를 활성화할 수 있습니다. 다음 예에서는 확인된 표현식 또는 확인된 블록을 사용하여 이전 합계 계산으로 인해 발생한 오버플로를 런타임에 감지하는 방법을 보여줍니다. 두 예제 모두 오버플로 예외를 발생시킵니다.

// If the previous sum is attempted in a checked environment, an 
// OverflowException error is raised.

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}
로그인 후 복사

unchecked를 사용하여 오버플로 검사를 취소할 수 있습니다.

이 예에서는 selected를 사용하여 런타임 오버플로 검사를 활성화하는 방법을 보여줍니다.

class OverFlowTest
{
    // Set maxIntValue to the maximum value for integers.
    static int maxIntValue = 2147483647;

    // Using a checked expression.
    static int CheckedMethod()
    {
        int z = 0;
        try
        {
            // The following line raises an exception because it is checked.
            z = checked(maxIntValue + 10);
        }
        catch (System.OverflowException e)
        {
            // The following line displays information about the error.
            Console.WriteLine("CHECKED and CAUGHT:  " + e.ToString());
        }
        // The value of z is still 0.
        return z;
    }

    // Using an unchecked expression.
    static int UncheckedMethod()
    {
        int z = 0;
        try
        {
            // The following calculation is unchecked and will not 
            // raise an exception.
            z = maxIntValue + 10;
        }
        catch (System.OverflowException e)
        {
            // The following line will not be executed.
            Console.WriteLine("UNCHECKED and CAUGHT:  " + e.ToString());
        }
        // Because of the undetected overflow, the sum of 2147483647 + 10 is 
        // returned as -2147483639.
        return z;
    }

    static void Main()
    {
        Console.WriteLine("\nCHECKED output value is: {0}",
                          CheckedMethod());
        Console.WriteLine("UNCHECKED output value is: {0}",
                          UncheckedMethod());
    }
    /*
   Output:
   CHECKED and CAUGHT:  System.OverflowException: Arithmetic operation resulted
   in an overflow.
      at ConsoleApplication1.OverFlowTest.CheckedMethod() 

   CHECKED output value is: 0
   UNCHECKED output value is: -2147483639
 */
}
로그인 후 복사

위 내용은 C#의 check와 unchecked 사용법입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!