003_Statements, Expressions, and Operators
13301 단어 C#
Statements
static void Main()
{
// Declaration statement.
int counter;
// Assignment statement.
counter = 1;
// Error! This is an expression, not an expression statement.
// counter + 1;
// Declaration statements with initializers are functionally
// equivalent to declaration statement followed by assignment statement:
int[] radii = { 15, 32, 108, 74, 9 }; // Declare and initialize an array.
const double pi = 3.14159; // Declare and initialize constant.
// foreach statement block that contains multiple statements.
foreach (int radius in radii)
{
// Declaration statement with initializer.
double circumference = pi * (2 * radius);
// Expression statement (method invocation). A single-line
// statement can span multiple text lines because line breaks
// are treated as white space, which is ignored by the compiler.
System.Console.WriteLine("Radius of circle #{0} is {1}. Circumference = {2:N2}",
counter, radius, circumference);
// Expression statement (postfix increment).
counter++;
} // End of foreach statement block
} // End of Main method body.
} // End of SimpleStatements class.
/*
Output:
Radius of circle #1 = 15. Circumference = 94.25
Radius of circle #2 = 32. Circumference = 201.06
Radius of circle #3 = 108. Circumference = 678.58
Radius of circle #4 = 74. Circumference = 464.96
Radius of circle #5 = 9. Circumference = 56.55
*/
Declaration statements - 선언문
// Variable declaration statements.
double area;
double radius = 2;
// Constant declaration statement.
const double pi = 3.14159;
Expression statements - 표현식 문
// Expression statement (assignment).
area = 3.14 * (radius * radius);
// Error. Not statement because no assignment:
//circ * 2;
// Expression statement (method invocation).
System.Console.WriteLine();
// Expression statement (new object creation).
System.Collections.Generic.List strings =
new System.Collections.Generic.List();
The empty statement - 빈 문장
void ProcessMessages()
{
while (ProcessMessage())
; // Statement needed here.
}
void F()
{
//...
if (done) goto exit;
//...
exit:
; // Statement needed here.
}
Embedded Statements - 내장형 문
// Recommended style. Embedded statement in block.
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
System.Console.WriteLine(s);
}
// Not recommended.
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
System.Console.WriteLine(s);
if(pointB == true)
//Error CS1023:
int radius = 5;
if (b == true)
{
// OK:
System.DateTime d = System.DateTime.Now;
System.Console.WriteLine(d.ToLongDateString());
}
Nested Statement Blocks - 중첩 문구 블록
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
if (s.StartsWith("CSharp"))
{
if (s.EndsWith("TempFolder"))
{
return s;
}
}
}
return "Not found.";
Unreachable Statements - 도달 불가 문
CS0162 경고가 발생합니다.
// An over-simplified example of unreachable code.
const int val = 5;
if (val < 4)
{
System.Console.WriteLine("I'll never write anything."); //CS0162
}
Expressions
표현식은 하나의 값, 대상, 방법, 명칭 공간으로 계산할 수 있는 하나 이상의 조작수와 하나 이상의 조작부호를 포함하는 서열이다.
((x < 10) && ( x > 5)) || ((x > 20) && (x < 25));
System.Convert.ToInt32("35");
Overflows - 넘침
checked 상하문 환경에서 산술 연산 결과가 넘치면 이상을 일으킬 수 있습니다.
unchecked 상하문 환경에서 산술 연산 결과가 넘치면 이상을 일으키지 않지만 계산 결과의 높은 위치는 절단되어 버려진다.
기본적으로 상수 값만 포함된 표현식은 연산 결과가 목표 유형을 넘치면 컴파일 오류를 일으킬 수 있습니다.표현식에 하나 이상의 비상량 값이 포함되어 있다면, 이 때 컴파일러는 넘침을 탐지하지 않고 컴파일 오류가 발생하지 않습니다.
checked
// 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);
// 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);
}
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("
CHECKED 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
*/
}
unchecked
class UncheckedDemo
{
static void Main(string[] args)
{
// int.MaxValue is 2,147,483,647.
const int ConstantMax = int.MaxValue;
int int1;
int int2;
int variableMax = 2147483647;
// The following statements are checked by default at compile time. They do not
// compile.
//int1 = 2147483647 + 10;
//int1 = ConstantMax + 10;
// To enable the assignments to int1 to compile and run, place them inside
// an unchecked block or expression. The following statements compile and
// run.
unchecked
{
int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);
// The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
Console.WriteLine(int1);
// The following statement is unchecked by default at compile time and run
// time because the expression contains the variable variableMax. It causes
// overflow but the overflow is not detected. The statement compiles and runs.
int2 = variableMax + 10;
// Again, the sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
Console.WriteLine(int2);
// To catch the overflow in the assignment to int2 at run time, put the
// declaration in a checked block or expression. The following
// statements compile but raise an overflow exception at run time.
checked
{
//int2 = variableMax + 10;
}
//int2 = checked(variableMax + 10);
// Unchecked sections frequently are used to break out of a checked
// environment in order to improve performance in a portion of code
// that is not expected to raise overflow exceptions.
checked
{
// Code that might cause overflow should be executed in a checked
// environment.
unchecked
{
// This section is appropriate for code that you are confident
// will not result in overflow, and for which performance is
// a priority.
}
// Additional checked code here.
}
}
}
Expression-bodied members - 표현식 구성원
expression-bodied method - 표현식체 방법
단일한 표현식을 포함하고 이 표현식은 이 방법의 반환값 유형과 일치하는 반환값을 되돌려줍니다.
using System;
public class Person
{
public Person(string firstName, string lastName)
{
fname = firstName;
lname = lastName;
}
private string fname;
private string lname;
public override string ToString() => $"{fname} {lname}".Trim();
public void DisplayName() => Console.WriteLine(ToString());
}
class Example
{
static void Main()
{
Person p = new Person("Mandy", "Dejesus");
Console.WriteLine(p);
p.DisplayName();
}
}
읽기 전용 속성 - 읽기 전용 속성
C# 6부터 표현식 정의를 사용하여 읽기 전용 속성을 생성할 수 있습니다.
PropertyType PropertyName => expression;
public class Location
{
private string locationName;
public Location(string name)
{
locationName = name;
}
public string Name => locationName;
}
Properties - 속성
C# 7부터 표현식 정의를 사용하여 속성의 get과 set 접근기를 생성할 수 있습니다.
public class Location
{
private string locationName;
public Location(string name) => Name = name;
public string Name
{
get => locationName;
set => locationName = value;
}
}
Constructors - 구조 함수
public class Location
{
private string locationName;
public Location(string name) => Name = name;
public string Name
{
get => locationName;
set => locationName = value;
}
}
Finalizers - 엔클로저
자원 방출
using System;
public class Destroyer
{
public override string ToString() => GetType().Name;
~Destroyer() => Console.WriteLine($"The {ToString()} destructor is executing.");
}
Indexers - 인덱스
using System;
using System.Collections.Generic;
public class Sports
{
private string[] types = { "Baseball", "Basketball", "Football",
"Hockey", "Soccer", "Tennis",
"Volleyball" };
public string this[int i]
{
get => types[i];
set => types[i] = value;
}
}
Operators - 조작자
Anonymous functions - 익명 함수
익명 함수는 내연의 문장이나 표현식으로delegate 형식이 나타나는 곳에 사용됩니다.
Equality comparisons - 동일 비교
Reference equality - 참조 동일
참조는 두 객체의 참조가 동일한 기본 객체를 참조하는 것과 같습니다.
using System;
class Test
{
public int Num { get; set; }
public string Str { get; set; }
static void Main()
{
Test a = new Test() { Num = 1, Str = "Hi" };
Test b = new Test() { Num = 1, Str = "Hi" };
bool areEqual = System.Object.ReferenceEquals(a, b);
// False:
System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
// Assign b to a.
b = a;
// Repeat calls with different results.
areEqual = System.Object.ReferenceEquals(a, b);
// True:
System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Value equality - 값이 같음
값은 동일합니다. 즉, 두 객체에 동일한 값이 포함됩니다.
int a = GetOriginalValue();
int b = GetCurrentValue();
// Test for value equality.
if( b == a)
{
// The two integers are equal.
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.