수색…


소개

C #에서 연산자 는 식 또는 문에서 하나 이상의 피연산자에 적용되는 프로그램 요소입니다. 증분 연산자 (++) 또는 새 연산자와 같은 하나의 피연산자를 사용하는 연산자는 단항 연산자라고합니다. 산술 연산자 (+, -, *, /)와 같이 두 개의 피연산자를 사용하는 연산자는 이진 연산자라고합니다. 하나의 연산자 인 조건부 연산자 (? :)는 세 개의 피연산자를 사용하며 C #의 유일한 삼항 연산자입니다.

통사론

  • 공용 정적 OperandType 연산자 operatorSymbol (OperandType operand1)
  • public static OperandType 연산자 operatorSymbol (OperandType operand1, OperandType2 operand2)

매개 변수

매개 변수 세부
operatorSymbol 오퍼레이터가 과부하가 걸리는 경우 (예 : +, -, /, *)
OperandType 오버로드 된 연산자에서 반환 할 형식입니다.
피연산자 1 연산을 수행하는 데 사용할 첫 번째 피연산자입니다.
피연산자 2 이진 연산을 수행 할 때 작업 수행에 사용되는 두 번째 피연산자.
성명 결과를 반환하기 전에 작업을 수행하는 데 필요한 선택적 코드입니다.

비고

모든 연산자는 static methods 로 정의되며 virtual 연산자가 아니며 상속되지 않습니다.

운영자 우선 순위

모든 사업자는 사업자가 속한 그룹 (동일한 그룹의 사업자는 동일한 우선 순위를 가짐)에 따라 특정한 "우선 순위"를가집니다. 일부 연산자는 다른 연산자보다 먼저 적용됩니다. 다음은 우선 순위별로 정렬 된 그룹 (각 연산자 포함) 목록입니다 (가장 높은 우선 순위).

  • 기본 연산자

    • ab - 회원 액세스.
    • a?.b - 널 조건부 멤버 액세스.
    • -> - 구성원 액세스와 결합 된 포인터 역 참조.
    • f(x) - 함수 호출.
    • a[x] - 인덱서.
    • a?[x] - 널 조건부 인덱서.
    • x++ - 후위 증가.
    • x-- - 후위 감소.
    • new - 인스턴스화 유형.
    • default(T) - 타입 T 의 기본 초기화 값을 반환합니다.
    • typeof - 피연산자의 Type 객체를 반환합니다.
    • checked - 숫자 오버 플로우 검사를 사용합니다.
    • unchecked - 숫자 오버 플로우 검사를 비활성화합니다.
    • delegate - 델리게이트 인스턴스를 선언하고 반환합니다.
    • sizeof - 타입 피연산자의 크기 (바이트)를 반환합니다.
  • 단항 연산자

    • +x - 반환 x .
    • -x - 숫자 부정.
    • !x - 논리적 부정.
    • ~x - 비트 단위로 보완 / 소멸자 선언.
    • ++x - 접두사 증가.
    • --x - 접두사 감소.
    • (T)x - 형 주조.
    • await - Task await .
    • &x -의 주소 (포인터)를 반환 x .
    • *x - 포인터 역 참조.
  • 곱셈 연산자

    • x * y - 곱셈.
    • x / y - 부문.
    • x % y - 모듈러스.
  • 첨가제 연산자

    • x + y - 더하기.
    • x – y - 빼기.
  • 비트 시프트 연산자

    • x << y - 왼쪽 시프트 비트.
    • x >> y - 오른쪽으로 시프트 비트.
  • 관계형 / 유형 테스트 연산자

    • x < y -보다 작음.
    • x > y -보다 큼.
    • x <= y -보다 작거나 같습니다.
    • x >= y - 크거나 같음.
    • is - 유형 호환성.
    • as - 타입 변환.
  • 평등 연산자

    • x == y - 평등.
    • x != y - 같지 않음.
  • 논리 AND 연산자

    • x & y - 논리 / 비트 AND.
  • 논리 XOR 연산자

    • x ^ y - 논리 / 비트 XOR.
  • 논리 OR 연산자

    • x | y - 논리 / 비트 OR.
  • 조건부 AND 연산자

    • x && y - 논리 AND를 단락.
  • 조건부 OR 연산자

    • x || y - 논리 OR 단락.
  • Null-coalescing 연산자

    • x ?? y - 널이 아닌 경우 x 리턴합니다. 그렇지 않으면 y 리턴합니다.
  • 조건부 연산자

    • x ? y : z - x 가 true이면 y 평가 / 반환합니다. 그렇지 않으면 z 평가합니다.

관련된 컨텐츠

오버로드 가능한 연산자

C #에서는 operator 키워드를 사용하여 정적 멤버 함수를 정의하여 사용자 정의 유형에서 연산자를 오버로드 할 수 있습니다.
다음 예제는 + 연산자의 구현을 보여줍니다.

Complex 를 나타내는 Complex 클래스가있는 경우 :

public struct Complex
{
    public double Real { get; set; }
    public double Imaginary { get; set; }
}

그리고이 클래스에 + 연산자를 사용하는 옵션을 추가하려고합니다. 즉 :

Complex a = new Complex() { Real = 1, Imaginary = 2 };
Complex b = new Complex() { Real = 4, Imaginary = 8 };
Complex c = a + b;

클래스에 대해 + 연산자를 오버로드해야합니다. 이것은 정적 함수와 operator 키워드를 사용하여 수행됩니다.

public static Complex operator +(Complex c1, Complex c2)
{
   return new Complex 
   { 
       Real = c1.Real + c2.Real,
       Imaginary = c1.Imaginary + c2.Imaginary 
   };
}

+ , - , * , / 와 같은 연산자는 모두 오버로드 될 수 있습니다. 여기에는 동일한 유형을 반환하지 않는 연산자도 포함됩니다 (예 : ==!= 은 부울 반환에도 불구하고 오버로드 될 수 있음). 쌍과 관련된 아래 규칙도 여기에 적용됩니다.

비교 연산자는 쌍으로 오버로드해야합니다 (예 : < 과부하 인 경우 > 또한 오버로드해야 함).

오버로드 가능한 연산자 (오버로드 할 수없는 연산자 및 일부 오버로드 가능한 연산자에 대한 제한 사항)의 전체 목록은 MSDN - 오버로드 가능한 연산자 (C # 프로그래밍 가이드) 에서 볼 수 있습니다.

7.0

operator is 오버로딩은 C # 7.0의 패턴 매칭 메커니즘과 함께 도입되었습니다. 자세한 내용은 패턴 일치 를 참조하십시오.

다음과 같이 정의 된 Cartesian

public class Cartesian
{
    public int X { get; }
    public int Y { get; }
}   

과부하 operator is 예를 들어 Polar 대해 정의 될 수 있습니다

public static class Polar
{
    public static bool operator is(Cartesian c, out double R, out double Theta)
    {
        R = Math.Sqrt(c.X*c.X + c.Y*c.Y);
        Theta = Math.Atan2(c.Y, c.X);
        return c.X != 0 || c.Y != 0;
    }
}

이런 식으로 사용할 수 있습니다.

var c = Cartesian(3, 4);
if (c is Polar(var R, *))
{
    Console.WriteLine(R);
}

(이 예는 Roslyn Pattern Matching Documentation 에서 가져온 것입니다)

관계 연산자

같음

제공된 피연산자 (인수)가 같은지 확인합니다.

"a" == "b"     // Returns false.
"a" == "a"     // Returns true.
1 == 0         // Returns false.
1 == 1         // Returns true.
false == true  // Returns false.
false == false // Returns true.

Java와는 달리, 평등 비교 연산자는 기본적으로 문자열로 작동합니다.

항등 비교 연산자는 암시 적 형변환이 서로간에 존재하는 경우 서로 다른 유형의 피연산자에 대해 작동합니다. 적합한 암시 적 형변환이없는 경우 명시 적 형변환을 호출하거나 호환 가능한 유형으로 변환하기위한 메서드를 사용할 수 있습니다.

1 == 1.0              // Returns true because there is an implicit cast from int to double.
new Object() == 1.0   // Will not compile.
MyStruct.AsInt() == 1 // Calls AsInt() on MyStruct and compares the resulting int with 1.

Visual Basic.NET과 달리 항등 비교 연산자는 항등 배정 연산자와 동일하지 않습니다.

var x = new Object();
var y = new Object();
x == y // Returns false, the operands (objects in this case) have different references.
x == x // Returns true, both operands have the same reference.

대입 연산자 ( = )와 혼동하지 마십시오.

값 유형의 경우, 연산자는 두 피연산자의 값이 동일하면 true 반환 true .
기준 유형의 운전자는 리턴 true 피연산자들 모두가 기준 (되지 값)에 동등한 경우. 단, 문자열 객체는 값의 동일성과 비교됩니다.

같지 않음

제공된 피연산자 여부를 확인은 동일하지 않다.

"a" != "b"     // Returns true.
"a" != "a"     // Returns false.
1 != 0         // Returns true.
1 != 1         // Returns false.
false != true  // Returns true.
false != false // Returns false.

var x = new Object();
var y = new Object();
x != y // Returns true, the operands have different references.
x != x // Returns false, both operands have the same reference.

이 연산자는 equals ( == ) 연산자와 반대 결과를 효과적으로 반환합니다.

보다 큰

첫 번째 피연산자가 두 번째 피연산자보다 큰지 확인합니다.

3 > 5    //Returns false.
1 > 0    //Returns true.
2 > 2    //Return false.

var x = 10;
var y = 15;
x > y    //Returns false.
y > x    //Returns true.

보다 작음

첫 번째 피연산자가 두 번째 피연산자보다 작은 지 확인합니다.

2 < 4     //Returns true.
1 < -3    //Returns false.
2 < 2     //Return false.

var x = 12;
var y = 22;
x < y    //Returns true.
y < x    //Returns false.

같음보다 큼

첫 번째 피연산자가 두 번째 피연산자보다 큰지 확인합니다.

7 >= 8    //Returns false.
0 >= 0    //Returns true.

평등보다 작음

첫 번째 피연산자가 두 번째 피연산자보다 작은 지 확인합니다.

2 <= 4    //Returns true.
1 <= -3    //Returns false.
1 <= 1     //Returns true. 

단락 연산자

정의에 따르면 단락 부울 연산자는 첫 번째 피연산자가 표현식의 전체 결과를 결정할 수없는 경우 두 번째 피연산자 만 계산합니다.

그것은 당신이 firstCondition로 && 연산자를 사용하는 경우 && secondCondition이 firstCondition가 true 인 경우에만 secondCondition을 평가하고 전체 결과 ofcource firstOperandsecondOperand 모두 true로 평가되는 경우에만 true가됩니다 것을 의미합니다. 이것은 여러 시나리오에서 유용합니다. 예를 들어 목록에 세 개 이상의 요소가 있지만 목록이 NullReferenceException으로 실행되지 않도록 초기화되었는지 확인해야합니다. 다음과 같이이 작업을 수행 할 수 있습니다.

bool hasMoreThanThreeElements = myList != null && mList.Count > 3;

mLList ! = null이 충족 될 때까지 mList.Count> 3 은 검사되지 않습니다.

논리적 AND

&& 는 표준 부울 AND ( & ) 연산자의 단락 대응입니다.

var x = true;
var y = false;

x && x // Returns true.
x && y // Returns false (y is evaluated).
y && x // Returns false (x is not evaluated).
y && y // Returns false (right y is not evaluated).

논리 OR

|| 표준 부울 OR ( | ) 연산자의 단락 대응 물입니다.

var x = true;
var y = false;

x || x // Returns true (right x is not evaluated).
x || y // Returns true (y is not evaluated).
y || x // Returns true (x and y are evaluated).
y || y // Returns false (y and y are evaluated).

사용 예

if(object != null && object.Property)
// object.Property is never accessed if object is null, because of the short circuit.
    Action1();
else
    Action2();

크기

반환 int 바이트 유형 *의 크기를 유지합니다.

sizeof(bool)    // Returns 1.
sizeof(byte)    // Returns 1.
sizeof(sbyte)   // Returns 1.
sizeof(char)    // Returns 2.
sizeof(short)   // Returns 2.
sizeof(ushort)  // Returns 2.
sizeof(int)     // Returns 4.
sizeof(uint)    // Returns 4.
sizeof(float)   // Returns 4.
sizeof(long)    // Returns 8.
sizeof(ulong)   // Returns 8.
sizeof(double)  // Returns 8.
sizeof(decimal) // Returns 16.

* 안전한 문맥에서 특정 원시 타입 만 지원합니다.

안전하지 않은 상황에서는 sizeof 를 사용하여 다른 기본 유형 및 구조체의 크기를 반환 할 수 있습니다.

public struct CustomType
{
    public int value;
}

static void Main()
{
    unsafe
    {
        Console.WriteLine(sizeof(CustomType)); // outputs: 4
    }
}

항등 연산자 오버로딩

평등 연산자 만 오버로드하는 것만으로는 충분하지 않습니다. 다른 상황에서 다음 모든 것을 호출 할 수 있습니다.

  1. object.Equalsobject.GetHashCode
  2. IEquatable<T>.Equals (옵션, 복싱을 피할 수 있음)
  3. operator ==operator != (옵션, 연산자 사용 가능)

Equals 재정의 할 때 GetHashCode 도 재정의해야합니다. Equals 구현할 때 여러 가지 특수한 경우가 있습니다. 유형이 다른 객체와 비교하고 자체와 비교하는 경우입니다.

오버라이드되지 않을 때 Equals 메소드와 == 연산자는 클래스와 구조체에 대해 다르게 동작합니다. 클래스의 경우 참조가 비교되고 구조체의 값에 대해 리플렉션을 통해 성능에 부정적인 영향을 줄 수있는 요소가 비교됩니다. == 재정의하지 않는 한 구조체를 비교하는 데 사용할 수 없습니다.

일반적으로 동등 연산은 다음 규칙을 따라야합니다.

  • 예외를 던져서 는 안됩니다.
  • 재귀는 : 항상 동일 A A (마찬가지하지 않을 수 있습니다 NULL 일부 시스템의 값).
  • Transitvity : A B 이고 B C 이면 A C 와 같습니다.
  • A B 와 같으면 AB 는 동일한 해시 코드를가집니다.
  • 상속 트리의 독립성은 다음과 같은 경우 BC 있는 인스턴스 Class2 상속 Class1 : Class1.Equals(A,B) 항상 호출과 같은 값을 반환해야합니다 Class2.Equals(A,B) .
class Student : IEquatable<Student>
{
    public string Name { get; set; } = "";

    public bool Equals(Student other)
    {
        if (ReferenceEquals(other, null)) return false;
        if (ReferenceEquals(other, this)) return true;
        return string.Equals(Name, other.Name);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;

        return Equals(obj as Student);
    }

    public override int GetHashCode()
    {
        return Name?.GetHashCode() ?? 0;
    }

    public static bool operator ==(Student left, Student right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Student left, Student right)
    {
        return !Equals(left, right);
    }
}

클래스 멤버 운영자 : 멤버 액세스

var now = DateTime.UtcNow;
//accesses member of a class.  In this case the UtcNow property.

클래스 멤버 연산자 : Null 조건부 멤버 액세스

var zipcode = myEmployee?.Address?.ZipCode;
//returns null if the left operand is null.  
//the above is the equivalent of:
var zipcode = (string)null;
if (myEmployee != null && myEmployee.Address != null)
    zipcode = myEmployee.Address.ZipCode;

클래스 멤버 연산자 : 함수 호출

var age = GetAge(dateOfBirth);
//the above calls the function GetAge passing parameter dateOfBirth.

클래스 멤버 연산자 : Aggregate Object Indexing

var letters = "letters".ToCharArray();
char letter = letters[1];
Console.WriteLine("Second Letter is {0}",letter);
//in the above example we take the second character from the array
//by calling letters[1]
//NB: Array Indexing starts at 0; i.e. the first letter would be given by letters[0].

클래스 멤버 연산자 : Null 조건부 인덱싱

var letters = null;
char? letter = letters?[1];
Console.WriteLine("Second Letter is {0}",letter);
//in the above example  rather than throwing an error because letters is null
//letter is assigned the value null

"독점 또는"운영자

"exclusive or"(짧은 XOR) 연산자는 다음과 같습니다. ^

이 연산자는 제공된 bool 중 하나만 참이면 true를 반환합니다.

true ^ false   // Returns true
false ^ true   // Returns true
false ^ false  // Returns false
true ^ true    // Returns false

비트 시프트 연산자

시프트 연산자를 사용하면 프로그래머는 비트를 모두 왼쪽이나 오른쪽으로 이동하여 정수를 조정할 수 있습니다. 다음 다이어그램은 값을 왼쪽으로 한 자리 이동시키는 영향을 보여줍니다.

왼쪽 - 시프트

uint value = 15;              // 00001111
 
uint doubled = value << 1;    // Result = 00011110 = 30
uint shiftFour = value << 4;  // Result = 11110000 = 240

오른쪽 시프트

uint value = 240;             // 11110000
 
uint halved = value >> 1;     // Result = 01111000 = 120
uint shiftFour = value >> 4;  // Result = 00001111 = 15

암시 적 캐스트 및 명시 적 캐스트 연산자

C #에서는 사용자 정의 형식이 explicitimplicit 키워드를 사용하여 할당 및 캐스팅을 제어 할 수 있습니다. 메소드의 서명은 다음 형식을 취합니다.

public static <implicit/explicit> operator <ResultingType>(<SourceType> myType)

메서드는 더 이상 인수를 사용할 수 없으며 인스턴스 메서드가 될 수도 없습니다. 그러나이 클래스는 정의 된 유형의 모든 비공개 멤버에 액세스 할 수 있습니다.

implicitexplicit 캐스트의 예 :

public class BinaryImage 
{
    private bool[] _pixels;

    public static implicit operator ColorImage(BinaryImage im)
    {
        return new ColorImage(im);
    }

    public static explicit operator bool[](BinaryImage im)
    {
        return im._pixels;
    }
}

다음 캐스트 구문 허용 :

var binaryImage = new BinaryImage();
ColorImage colorImage = binaryImage; // implicit cast, note the lack of type 
bool[] pixels = (bool[])binaryImage; // explicit cast, defining the type

형변환 연산자는 두 가지 방법으로 작업 할 수 있습니다. 즉, 형식 에서 유형으로 이동 하는 것입니다.

public class BinaryImage
{
    public static explicit operator ColorImage(BinaryImage im)
    {
        return new ColorImage(im);
    }

    public static explicit operator BinaryImage(ColorImage cm)
    {
        return new BinaryImage(cm);
    }
}

마지막으로, 유형 계층 구조 내에서 형변환에 관련 될 수있는 as 키워드는이 상황에서 유효 하지 않습니다. explicit 또는 implicit 캐스트를 정의한 후에도 다음을 수행 할 수 없습니다.

ColorImage cm = myBinaryImage as ColorImage;

컴파일 오류가 발생합니다.

배정 된 이진 연산자

C #에는 연산자와 결과를 평가하고 결과를 원래 변수에 할당하기 위해 = 기호와 결합 할 수있는 몇 가지 연산자가 있습니다.

예:

x += y

와 같다

x = x + y

배정 연산자 :

  • +=
  • -=
  • *=
  • /=
  • %=
  • &=
  • |=
  • ^=
  • <<=
  • >>=

? : 삼항 연산자

부울 식의 값에 따라 두 값 중 하나를 반환합니다.

통사론:

condition ? expression_if_true : expression_if_false;

예:

string name = "Frank";
Console.WriteLine(name == "Frank" ? "The name is Frank" : "The name is not Frank");

삼항 연산자는 복합 삼항 표현식을 사용할 수있게하는 오른쪽 연관입니다. 이것은 부모 삼항 방정식의 참 또는 거짓 위치에 추가 삼항 방정식을 추가하여 수행됩니다. 가독성을 보장하기 위해주의를 기울여야하지만, 일부 상황에서는이를 사용하는 것이 유용 할 수 있습니다.

이 예제에서 복합 삼항 연산은 clamp 함수를 평가하고 범위 내에 있으면 현재 값을 반환하고 범위 미만이면 min 값을 반환하고 범위를 초과하면 max 값을 반환합니다.

light.intensity = Clamp(light.intensity, minLight, maxLight);

public static float Clamp(float val, float min, float max)
{
    return (val < min) ? min : (val > max) ? max : val;
}

삼항 연산자는 다음과 같이 중첩 될 수 있습니다.

a ? b ? "a is true, b is true" : "a is true, b is false" : "a is false"

// This is evaluated from left to right and can be more easily seen with parenthesis:

a ? (b ? x : y) : z

// Where the result is x if a && b, y if a && !b, and z if !a

복합 삼항 문장을 작성할 때 가독성을 높이기 위해 괄호 또는 들여 쓰기를 사용하는 것이 일반적입니다.

expression_if_trueexpression_if_false 의 유형은 동일해야하며, 하나에서 다른 하나로 암시 적 변환이 있어야합니다.

condition ? 3 : "Not three"; // Doesn't compile because `int` and `string` lack an implicit conversion.

condition ? 3.ToString() : "Not three"; // OK because both possible outputs are strings.

condition ? 3 : 3.5; // OK because there is an implicit conversion from `int` to `double`. The ternary operator will return a `double`.

condition ? 3.5 : 3; // OK because there is an implicit conversion from `int` to `double`. The ternary operator will return a `double`.

유형 및 변환 요구 사항은 자신의 클래스에도 적용됩니다.

public class Car
{}

public class SportsCar : Car
{}

public class SUV : Car
{}

condition ? new SportsCar() : new Car(); // OK because there is an implicit conversion from `SportsCar` to `Car`. The ternary operator will return a reference of type `Car`.

condition ? new Car() : new SportsCar(); // OK because there is an implicit conversion from `SportsCar` to `Car`. The ternary operator will return a reference of type `Car`.

condition ? new SportsCar() : new SUV(); // Doesn't compile because there is no implicit conversion from `SportsCar` to SUV or `SUV` to `SportsCar`. The compiler is not smart enough to realize that both of them have an implicit conversion to `Car`.

condition ? new SportsCar() as Car : new SUV() as Car; // OK because both expressions evaluate to a reference of type `Car`. The ternary operator will return a reference of type `Car`.

유형

형식에 대한 System.Type 개체를 가져 System.Type .

System.Type type = typeof(Point)        //System.Drawing.Point      
System.Type type = typeof(IDisposable)  //System.IDisposable
System.Type type = typeof(Colors)       //System.Drawing.Color
System.Type type = typeof(List<>)       //System.Collections.Generic.List`1[T]

런타임 유형을 가져 오려면 GetType 메서드를 사용하여 현재 인스턴스의 System.Type 을 가져옵니다.

연산자 typeof 는 컴파일 할 때 지정되는 매개 변수로 형식 이름을 사용합니다.

public class Animal {} 
public class Dog : Animal {}

var animal = new Dog();

Assert.IsTrue(animal.GetType() == typeof(Animal)); // fail, animal is typeof(Dog) 
Assert.IsTrue(animal.GetType() == typeof(Dog));    // pass, animal is typeof(Dog)
Assert.IsTrue(animal is Animal);                   // pass, animal implements Animal

기본 연산자

값 유형 (여기서 T : struct)

struct , enum 선언 된 사용자 정의 유형은 물론 char , intfloat 와 같은 기본 제공 기본 데이터 유형. 기본값은 new T() .

default(int)            // 0
default(DateTime)       // 0001-01-01 12:00:00 AM
default(char)           // '\0' This is the "null character", not a zero or a line break.
default(Guid)           // 00000000-0000-0000-0000-000000000000
default(MyStruct)       // new MyStruct()

// Note: default of an enum is 0, and not the first *key* in that enum
// so it could potentially fail the Enum.IsDefined test
default(MyEnum)         // (MyEnum)0

참조 유형 (여기서 T : 클래스)

모든 class , interface , 배열 또는 대리자 유형. 기본값은 null .

default(object)         // null
default(string)         // null
default(MyClass)        // null
default(IDisposable)    // null
default(dynamic)        // null

운영자

variable , type 또는 member 의 정규화되지 않은 이름을 나타내는 문자열을 반환합니다.

int counter = 10;
nameof(counter); // Returns "counter"
Client client = new Client();
nameof(client.Address.PostalCode)); // Returns "PostalCode"

nameof 연산자는 C # 6.0에 도입되었습니다. 컴파일 타임에 평가되고 반환 된 문자열 값은 컴파일러에서 인라인으로 삽입되므로 상수 문자열을 사용할 수있는 대부분의 경우에 사용할 수 있습니다 (예 : switch 문, 속성 등의 case 레이블). ). raising 및 로깅 예외, 속성, MVC 액션 링크 등의 경우 유용 할 수 있습니다.

?. (Null 조건부 연산자)

6.0

C # 6.0에서 소개 된 Null 조건부 연산자 ?. NullReferenceException 을 던지는 대신 왼쪽에있는 표현식이 null 평가되면 즉시 null 반환합니다. 왼쪽면이 null 이 아닌 값으로 평가되면 정상과 같이 처리 . 운영자. null 돌려주는 경우가 있기 (위해) 때문에, 반환 null 형태는 항상 nullable 형입니다. 즉, 구조체 또는 기본 유형의 경우 Nullable<T> 래핑됩니다.

var bar = Foo.GetBar()?.Value; // will return null if GetBar() returns null
var baz = Foo.GetBar()?.IntegerValue; // baz will be of type Nullable<int>, i.e. int?

이벤트를 발생시킬 때 유용합니다. 일반적으로 null 검사하는 if 문에서 이벤트 호출을 래핑하고 나중에 이벤트를 발생시켜 경쟁 조건이 발생할 수 있습니다. Null 조건부 연산자를 사용하면 다음과 같이 수정할 수 있습니다.

event EventHandler<string> RaiseMe;
RaiseMe?.Invoke("Event raised");

접미사 및 접두어 증가 및 감소

후위 증가 X++x1 을 더합니다

var x = 42;
x++;
Console.WriteLine(x); // 43

후위 감소 X-- 는 - 하나를 뺍니다

var x = 42
x--; 
Console.WriteLine(x); // 41

++x 는 접두사 증분이라고 부르며 ++x 의 값을 증가시키고 x를 반환하며 x++x++ 의 값을 반환 한 다음 증분합니다

var x = 42;
Console.WriteLine(++x); // 43
System.out.println(x); // 43

동안

var x = 42;
Console.WriteLine(x++); // 42
System.out.println(x); // 43

둘 다 for 루프에서 일반적으로 사용됩니다.

for(int i = 0; i < 10; i++)
{
}

=> 람다 연산자

3.0

=> 연산자는 할당 연산자 = 와 동일한 우선 순위를 가지며 오른쪽 연관입니다.

이것은 람다 식을 선언하는 데 사용되며 LINQ 쿼리 와 함께 널리 사용됩니다.

string[] words = { "cherry", "apple", "blueberry" };

int shortestWordLength = words.Min((string w) => w.Length); //5

LINQ 확장 또는 쿼리에서 사용되는 경우 일반적으로 개체 유형은 컴파일러에서 유추 할 때 건너 뛸 수 있습니다.

int shortestWordLength = words.Min(w => w.Length); //also compiles with the same result

람다 연산자의 일반적인 형식은 다음과 같습니다.

(input parameters) => expression

람다 식의 매개 변수는 => 연산자 앞에 지정되며 실행될 실제 식 / 문 / 블록은 연산자의 오른쪽에 있습니다.

// expression
(int x, string s) => s.Length > x

// expression
(int x, int y) => x + y

// statement
(string x) => Console.WriteLine(x)

// block
(string x) => {
        x += " says Hello!";
        Console.WriteLine(x);
    }

이 연산자를 사용하면 명시 적 메서드를 작성하지 않고도 대리자를 쉽게 정의 할 수 있습니다.

delegate void TestDelegate(string s);

TestDelegate myDelegate = s => Console.WriteLine(s + " World");

myDelegate("Hello");

대신에

void MyMethod(string s)
{
    Console.WriteLine(s + " World");
}

delegate void TestDelegate(string s);

TestDelegate myDelegate = MyMethod;

myDelegate("Hello");

할당 연산자 '='

대입 연산자 = 는 왼쪽 피연산자의 값을 오른쪽 피연산자의 값으로 설정하고 그 값을 반환합니다.

int a = 3;     // assigns value 3 to variable a
int b = a = 5; // first assigns value 5 to variable a, then does the same for variable b
Console.WriteLine(a = 3 + 4); // prints 7

?? Null-Coalescing 연산자

Null-Coalescing 연산자 ?? null가 아닌 경우 왼쪽을 반환합니다. null의 경우, 오른쪽이 돌려 주어집니다.

object foo = null;
object bar = new object();

var c = foo ?? bar;
//c will be bar since foo was null

The ?? 연산자를 체인화하여 if 점검을 제거 할 수 있습니다.

//config will be the first non-null returned.
var config = RetrieveConfigOnMachine() ??
             RetrieveConfigFromService() ??
             new DefaultConfiguration();


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow