C# 베이스 연산자

3151 단어
1. 조건 연산자
조건 연산자(?:)는 삼원(목) 연산자라고도 부르며if...else 구조의 간소화 형식으로 끼워 넣을 수 있습니다.
 
 
  
int x = 1; 
string s = x + ""; ; 
s += (x == 1 ? "man" : "men"); 
Console.WriteLine(s);// 1man 

2, checked 및 unchecked
 
  
byte b = 255; 

    b++; 

Console.WriteLine(b.ToString());// 0 

그러나byte는 0-255의 수를 포함할 수 있기 때문에++ 이후에 b가 넘칠 수 있습니다.따라서 코드 블록을 checked로 표시하면 CLR은 오버플로우 검사를 실행하고 오버플로우 Exception 이상을 던집니다.
다음과 같습니다.
 
  
byte b = 255; 
checked 

    b++; 

Console.WriteLine(b.ToString());// OverflowException ,  

넘침 검사를 금지하려면 unchecked:
 
  
byte b = 255; 
unchecked 

    b++; 

Console.WriteLine(b.ToString());// 0,  

3、is
is 연산자는 대상이 특정한 유형과 호환되는지 검사할 수 있습니다.호환성은 객체가 유형이거나 해당 유형에서 파생되었음을 나타냅니다.
 
  
string i = "hello i..."; 
if (i is object) 

    Console.WriteLine("i is an object...");//  


4、as
as 연산자는 인용 형식의 현식 형식 변환을 실행하는 데 사용됩니다. (string은 인용 형식입니다.)변환할 유형이 지정한 유형과 호환되면 변환이 성공적으로 진행됩니다.유형이 호환되지 않으면 as 연산자가 널을 반환합니다.
 
  
string i = "hello i..."; 
if (i is object) 

    object obj = i as object;//  
    Console.WriteLine(obj is string ? "obj is string..." : "obj is not string...");// obj is string... 
}

5、sizeof
sizeof 연산자는 stack 중간값 유형에 필요한 길이(바이트 단위)를 결정합니다.
 
  
int byteSize = sizeof(byte);// 1 
int charSize = sizeof(char);// 2 
int uintSize = sizeof(uint);// 4 
int intSize = sizeof(int);// 4 

6、typeof
typeof 연산자는 GetType() 방법과 결합하여 클래스의 속성, 방법 등을 반사하는 데 자주 사용된다.
 
  
Type intType = typeof(int); 
System.Reflection.MethodInfo[] methodInfo = intType.GetMethods(); 
methodInfo.ToList().ForEach(x => Console.WriteLine(x.Name));// int  

7. 비어 있는 유형 및 연산자
만약 그 중의 한 조작수나 두 조작수가 모두null이라면 그 결과는null이다. 예를 들어 다음과 같다.
 
  
int? a = null; 
int? b = a + 4;//b = null 
int? c = a * 5;//c = null 

그러나 비울 수 있는 유형을 비교할 때 하나의 조작수가null이면 비교의 결과는false이다.그러나 조건이 false라고 해서 이 조건의 대립면이true라고 생각해서는 안 된다.예:

     
  
int? a = null; 
int? b = -5; 
if (a >= b) 
    Console.WriteLine("a > = b"); 
else 
    Console.WriteLine("a < b");//

8, 빈 결합 연산자
예를 들면 다음과 같습니다.
 
  
int? a = null;// , Int null 
int b; 
b = a ?? 1; 
[csharp] 
Console.WriteLine(b);// 1 
a = 3; 
b = a ?? 10; 
Console.WriteLine(b);// 10 

좋은 웹페이지 즐겨찾기