Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Praise for C# 2.0: Practical Guide for Programmers 2005 phần 5 pptx
MIỄN PHÍ
Số trang
26
Kích thước
436.1 KB
Định dạng
PDF
Lượt xem
1578

Praise for C# 2.0: Practical Guide for Programmers 2005 phần 5 pptx

Nội dung xem thử

Mô tả chi tiết

■ 5.2 Assignment Operators 85

The destination Variable and the source Expression must be type compatible. The

Variable can store either a simple data value or an object reference.

Assignments of Simple Values

Examples:

int a, b, c;

a = 1; // OK.

b = a; // OK.

a = c; // Error: Variable must be initialized before used.

1 = a; // Error: Destination must be a variable.

c = (a + b); // OK.

(a + b) = c; // Error: Destination must be a variable.

The assignment operator has the lowest precedence, allowing the expression on the right￾hand side to be evaluated before any assignment:

int a;

a = 1;

System.Console.WriteLine(a);

a = a - 1; // - has higher precedence than =

System.Console.WriteLine(a);

a = 2 + a * 3; // (2 + (0 * 3))

System.Console.WriteLine(a);

Output:

1

0

2

Assignments of References

Examples:

Id id1 = new Id("Frank", 1);

Id id2 = new Id("Emma", 2);

id2 = id1;

Copying references by assignment does not copy the content of the source object, only

its reference. Now id2 refers to the same Id object as id1, and the previous object

Id("Emma", 2) is eligible for garbage collection.

86 Chapter 5: Operators, Assignments, and Expressions ■

5.2.2 Multiple Assignments

An assignment always returns the value of the expression on the right-hand side as a result.

Therefore, initializing several variables to a common value or reference using multiple

assignment statements:

int a, b, c;

a = 1; b = 1; c = 1;

can be reduced to a single statement using multiple assignments as shown:

a = b = c = 1; // a = (b = (c = 1));

The preceding example illustrates the importance of right associativity for the assignment

operator.

5.3 Conditional Operator

The conditional operator evaluates a boolean expression, and, depending on its

EBNF resultant value (either true or false), executes one of two expressions as defined here:

ConditionalOperator = Condition "?" ExprIfConditionTrue ":" ExprIfConditionFalse.

The conditional operator, therefore, is equivalent to a simple if-else statement:

if ( Condition )

ExprIfConditionTrue

else

ExprIfConditionFalse

For example:

minimum = a < b ? a : b;

is equivalent to:

if (a < b)

minimum = a;

else

minimum = b;

Another example:

absolute = a < 0 ? -a : a;

Tải ngay đi em, còn do dự, trời tối mất!