Understanding Operators
Số trang: 6
Loại file: pdf
Dung lượng: 25.21 KB
Lượt xem: 1
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
Sự hiểu biết sử dụng Bạn sử dụng toán tử để kết hợp với nhau thành các biểu thức toán hạng. Mỗi nhà khai thác có ngữ nghĩa riêng của nó phụ thuộc vào loại nó làm việc với.
Nội dung trích xuất từ tài liệu:
Understanding OperatorsUnderstanding OperatorsYou use operators to combine operands together into expressions. Each operator has itsown semantics dependent on the type it works with. For example, the + operator means“add” when used with numeric types, or “concatenate” when used with strings.Each operator symbol has a precedence. For example, the * operator has a higherprecedence than the + operator. This means that the expression a + b * c is the same as a+ (b * c).Each operator symbol also has an associativity to define whether the operator evaluatesfrom left to right or from right to left. For example, the = operator is right-associative (itevaluates from right to left), so a = b = c is the same as a = (b = c).NOTEThe right-associativity of the = operator allows you to perform multiple assignments inthe same statement. For example, you can initialize several variables to the same valuelike this:int a, b, c, d, e; a = b = c = d = e = 99;The expression e = 99 is evaluated first. The result of the expression is the value that wasassigned (99), which is then assigned to d, c, b, and finally a in that order.A unary operator is an operator that has just one operand. For example, the incrementoperator (++) is a unary operator.A binary operator is an operator that has two operands. For example, the multiplicationoperator (*) is a binary operator.Operator ConstraintsC# allows you to overload most of the existing operator symbols for your own types.When you do this, the operators you implement automatically fall into a well-definedframework with the following rules: • You cannot change the precedence and associativity of an operator. The precedence and associativity are based on the operator symbol (for example, +) and not on the type (for example, int) on which the operator symbol is being used. Hence, the expression a + b * c is always the same as a + (b * c), regardless of the type of a, b, and c. • You cannot change the multiplicity of an operator (the number of operands). For example, * (the symbol for multiplication), is a binary operator. If you declare a * operator for your own type, it must be a binary operator. • You cannot invent new operator symbols. For example, you cant create a new operator symbol, such as ** for raising one number to the power of another number. Youd have to create a method for that. • You cant change the meaning of operators when applied to built-in types. For example, the expression 1 + 2 has a predefined meaning and youre not allowed to override this meaning. If you could do this, things would be too complicated! • There are some operator symbols that you cant overload. For example, you cant overload the dot operator (member access). Again, if you could do this, it would lead to unnecessary complexity. TIP You can use indexers to simulate [ ] as an operator. Similarly, you can use properties to simulate = (assignment) as an operator, and you can use delegates to simulate a function call as an operator.Overloaded OperatorsTo define your own operator behavior, you must overload a selected operator. You usemethod-like syntax with a return type and parameters, but the name of the method is thekeyword operator together with the operator symbol you are declaring. For example,heres a user-defined struct called Hour that defines a binary + operator to add togethertwo instances of Hour:struct Hour{ public Hour(int initialValue) { this.value = initialValue; } public static Hour operator+ (Hour lhs, Hour rhs) { return new Hour(lhs.value + rhs.value); } ... private int value;}Notice the following: • The operator is public. All operators must be public. • The operator is static. All operators must be static. Operators are never polymorphic, and cannot use the virtual, abstract, override, or sealed modifiers. • A binary operator (such as + shown above) has two explicit arguments and a unary operator has one explicit argument (C++ programmers should note that operators never have a hidden this parameter). TIP When declaring highly stylized functionality (such as operators), it is useful to adopt a naming convention for the parameters. For example, developers often use lhs and rhs (acronyms for left-hand side and right-hand side, respectively) for binary operators.When you use the + operator on two expressions of type Hour, the C# compilerautomatically converts your code into a call to the user-defined operator. The C#compiler converts this:Hour Example(Hour a, Hour b){ return a + b;}Into this:Hour Example(Hour a, Hour b){ return Hour.operator+(a,b); // pseudocode}Note, however, that this syntax is pseudocode and not valid C#. You can use a binaryoperator only in its standard infix notation (with the symbol between the operands).There is one final rule you must follow when declaring an operator otherwise your codewill not compile: At least one of the parameters should always be of the containing type.In the previous operator+ example for the Hour class, one of the parameters, a or b, mustbe an Hour object. In this example, both parameters are Hour objects. However, therecould be times when you want to define additional implementations of operator+ that addan integer (a number of hours) to an Hour object—the first parameter could be Hour, andthe second parameter could be the integer. This rule makes it easier for the compiler toknow where to look when trying to resolve an operator invocation, and it also ensuresthat you cant change the meaning of the built-in operators.Creating Symmetric OperatorsIn the previous section, you saw how to declare a binary + operator to add together twoin ...
Nội dung trích xuất từ tài liệu:
Understanding OperatorsUnderstanding OperatorsYou use operators to combine operands together into expressions. Each operator has itsown semantics dependent on the type it works with. For example, the + operator means“add” when used with numeric types, or “concatenate” when used with strings.Each operator symbol has a precedence. For example, the * operator has a higherprecedence than the + operator. This means that the expression a + b * c is the same as a+ (b * c).Each operator symbol also has an associativity to define whether the operator evaluatesfrom left to right or from right to left. For example, the = operator is right-associative (itevaluates from right to left), so a = b = c is the same as a = (b = c).NOTEThe right-associativity of the = operator allows you to perform multiple assignments inthe same statement. For example, you can initialize several variables to the same valuelike this:int a, b, c, d, e; a = b = c = d = e = 99;The expression e = 99 is evaluated first. The result of the expression is the value that wasassigned (99), which is then assigned to d, c, b, and finally a in that order.A unary operator is an operator that has just one operand. For example, the incrementoperator (++) is a unary operator.A binary operator is an operator that has two operands. For example, the multiplicationoperator (*) is a binary operator.Operator ConstraintsC# allows you to overload most of the existing operator symbols for your own types.When you do this, the operators you implement automatically fall into a well-definedframework with the following rules: • You cannot change the precedence and associativity of an operator. The precedence and associativity are based on the operator symbol (for example, +) and not on the type (for example, int) on which the operator symbol is being used. Hence, the expression a + b * c is always the same as a + (b * c), regardless of the type of a, b, and c. • You cannot change the multiplicity of an operator (the number of operands). For example, * (the symbol for multiplication), is a binary operator. If you declare a * operator for your own type, it must be a binary operator. • You cannot invent new operator symbols. For example, you cant create a new operator symbol, such as ** for raising one number to the power of another number. Youd have to create a method for that. • You cant change the meaning of operators when applied to built-in types. For example, the expression 1 + 2 has a predefined meaning and youre not allowed to override this meaning. If you could do this, things would be too complicated! • There are some operator symbols that you cant overload. For example, you cant overload the dot operator (member access). Again, if you could do this, it would lead to unnecessary complexity. TIP You can use indexers to simulate [ ] as an operator. Similarly, you can use properties to simulate = (assignment) as an operator, and you can use delegates to simulate a function call as an operator.Overloaded OperatorsTo define your own operator behavior, you must overload a selected operator. You usemethod-like syntax with a return type and parameters, but the name of the method is thekeyword operator together with the operator symbol you are declaring. For example,heres a user-defined struct called Hour that defines a binary + operator to add togethertwo instances of Hour:struct Hour{ public Hour(int initialValue) { this.value = initialValue; } public static Hour operator+ (Hour lhs, Hour rhs) { return new Hour(lhs.value + rhs.value); } ... private int value;}Notice the following: • The operator is public. All operators must be public. • The operator is static. All operators must be static. Operators are never polymorphic, and cannot use the virtual, abstract, override, or sealed modifiers. • A binary operator (such as + shown above) has two explicit arguments and a unary operator has one explicit argument (C++ programmers should note that operators never have a hidden this parameter). TIP When declaring highly stylized functionality (such as operators), it is useful to adopt a naming convention for the parameters. For example, developers often use lhs and rhs (acronyms for left-hand side and right-hand side, respectively) for binary operators.When you use the + operator on two expressions of type Hour, the C# compilerautomatically converts your code into a call to the user-defined operator. The C#compiler converts this:Hour Example(Hour a, Hour b){ return a + b;}Into this:Hour Example(Hour a, Hour b){ return Hour.operator+(a,b); // pseudocode}Note, however, that this syntax is pseudocode and not valid C#. You can use a binaryoperator only in its standard infix notation (with the symbol between the operands).There is one final rule you must follow when declaring an operator otherwise your codewill not compile: At least one of the parameters should always be of the containing type.In the previous operator+ example for the Hour class, one of the parameters, a or b, mustbe an Hour object. In this example, both parameters are Hour objects. However, therecould be times when you want to define additional implementations of operator+ that addan integer (a number of hours) to an Hour object—the first parameter could be Hour, andthe second parameter could be the integer. This rule makes it easier for the compiler toknow where to look when trying to resolve an operator invocation, and it also ensuresthat you cant change the meaning of the built-in operators.Creating Symmetric OperatorsIn the previous section, you saw how to declare a binary + operator to add together twoin ...
Tìm kiếm theo từ khóa liên quan:
ngôn ngữ lập trình lập trình ngôn ngữ C# C# Summarizing Keyword Combinations Understanding OperatorsGợi ý tài liệu liên quan:
-
Giáo trình Lập trình hướng đối tượng: Phần 2
154 trang 271 0 0 -
Bài thuyết trình Ngôn ngữ lập trình: Hệ điều hành Window Mobile
30 trang 261 0 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 261 0 0 -
Giáo trình Lập trình cơ bản với C++: Phần 1
77 trang 230 0 0 -
Bài giảng Một số hướng nghiên cứu và ứng dụng - Lê Thanh Hương
13 trang 221 0 0 -
Giáo án Tin học lớp 11 (Trọn bộ cả năm)
125 trang 214 1 0 -
NGÂN HÀNG CÂU HỎI TRẮC NGHIỆM THIẾT KẾ WEB
8 trang 202 0 0 -
Bài tập lập trình Windows dùng C# - Bài thực hành
13 trang 177 0 0 -
Giáo trình Lập trình C căn bản: Phần 1
64 trang 169 0 0 -
Bài giảng Nhập môn về lập trình - Chương 1: Giới thiệu về máy tính và lập trình
30 trang 162 0 0