C# 2005 Programmer’s Reference - chapter 3

Tham khảo tài liệu 'c# 2005 programmer’s reference - chapter 3', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 52 CHAPTER 3 General Coding using System using WpfControls using AcmeControls namespace MyProgramNamespace class MyClass void DoSomething button new dial new NOTE The keyword using is also used in the context of the Dispose Pattern see Chapter 22 Memory Management . Use the Conditional Operator Scenario Problem You want to choose between two alternate values within a single statement. Solution Use the conditional operator sometimes called the ternary operator for its three arguments . For example condition a b is shorthand for if condition do a else do b . class Program static void Main string args bool condition true int x condition 13 14 x is 0 x you can also embed the condition in other statements Condition is 0 condition TRUE FALSE Use the Null-Coalescing Operator 53 This program prints the following output x is 13 Condition is TRUE NOTE This operator is not limited to just assignments. You can also use it in situa tions like this bool actionSucceeded CheckIfActionSucceeded actionSucceeded ReportSucceeded ReportFailed Use the Null-Coalescing Operator Scenario Problem You want to simplify checking for null values. This is a common situation where you need to check for a null value before you use a variable. Solution The null-coalescing operator can simplify the syntax a bit. int n null object obj Hello int x 13 short for if n null o n else o -1 int o n -1 object obj2 obj ok doesn t make sense since x can t be null int y x -1 o 0 o obj2 0 obj2 The output is as follows o -1 obj2 Hello 54 CHAPTER 3 General Coding Add Methods to Existing Types with Extension Methods Scenario Problem You want to add a method to an existing type for which you cannot change the source code so that the syntax you use is . Solution Create an extension method using special .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.