C # Study Notes 2,

Source: Internet
Author: User

C # Study Notes 2,

1.Namespace Declaration: a namespace is a special classification mechanism that groups all types related to a specific function. Generally, the outer namespace is specified as the company name, which is the product name in turn, and finally the functional area, such as Microsoft. Win32.Networking. The namespace can contain periods, which makes the namespace "appear" layered. However, this only improves readability because the compiler considers that all namespaces are flushed at the same level,

For example, System. Collections. Generics seems to be included in the System. Collections namespace, but for the compiler, they are two completely different namespaces.

 

2.The difference between using import: The difference between placing the using command on the top of the file and placing the using command on the top of the namespace Declaration is that, the using command of the latter is only valid in the namespace you declare. mlchaelis. A new namespace is declared outside the EssentialCSharp namespace, and the new namespace will not be affected by using. the impact of System commands. However, code is rarely written like this, especially as agreed, each file should only have a type declaration.

 

3.Using alias: Use the using command to get an alias for the namespace or type. The alias (alias) is an alternative name that can be used within the range of the using command. The two most common reasons for using aliases are to eliminate two types of ambiguity and abbreviations of the same name.

 

4.Program entry method: the Main () method supports int return values, rather than vold return. the return value is optional for the Main () statement. however, if you use it. the program can return a status code to the caller (the caller can be a script or a batch file ). According to the Conventions, a non-zero return value indicates an error. Although all command line parameters can be passed to Main () through a string array, sometimes we may need to access those parameters from a method different from Main, in this case, you can use System. environment. getCommandLineArgs () method. This method uses the same method as Main (string [] args) to pass the parameter to Main () to return the command line parameter.

 

5.C #4.0 added:

(1) optional parameters: the optional parameters must be placed after all required parameters (parameters without default values. In addition, the default value must be a constant or a value that can be determined during compilation, which greatly limits the application of "optional parameters.

For example: DirectoryCountLines (string directory, string extension = "*. cs ")

(2) named parameters: using the named parameter disk, the caller can explicitly specify the parameter name. and assign a value to this parameter, instead of deciding which value is assigned to which parameter based on the parameter order as before,

For example: DisplayGreeting (firstName: "Lucy", lastName: "Jack ");

Public void DisplayGreeting (string firstName, string middleName = default (string), string lastName = default (string ))

{

... Omitted

}

If a single site has a large number of parameters and many of them are optional (this is common when accessing the Microsoft COM Library ), the naming parameter syntax will certainly bring a lot of convenience. However, it should be noted that the cost of this convenience is to sacrifice the flexibility of the method interface. In the past {at least C #), the parameter name can be freely changed, this will not cause compilation failure of the calling code. however, after a named parameter is added, the parameter name becomes part of the method interface. Changing the name will make the code using the named parameter unable to be compiled.

 

6.If method overloading, optional parameters, and named parameters are used together, it is difficult for us to see which method is called at a glance, except for all parameters) there is exactly a corresponding real parameter (whether based on the name or location), and the real parameter has a compatible type, it is said that a call is applicable to (compatible with) a method. Although this limits the number of callable methods, it is not sufficient to uniquely identify the method. To further differentiate the method, the compiler only uses the parameters explicitly identified by the caller, ignore all optional parameters not specified by the caller. Therefore, if a method has an optional parameter and both methods are applicable, the compiler selects a method without optional parameters.

When the compiler selects the final called method from a series of "applicable" methods, it depends on which method is most specific and only one method can fully match the parameters passed by the caller. Therefore, this method always has the highest priority.

For example, if the caller passes an int, the method that accepts double will take precedence over the method that accepts the object. This is because double is more specific than the object. If there are multiple applicable methods, however, the compiler reports an error that indicates that the call is ambiguous. In order writing, it is best to use explicit transformation to help others understand the target method you want to call.

 

7.Try-catch-finally usage: catch is from specific to General. If a specific catch Block is added after the catch Block of Exception is caught, the compiler reports a warning message, indicates that the specific catch Block will never be executed. A catch block without a specified data type is called a generalized catch block. It is equivalent to a catch block that obtains the object data type.

For example, catch (object exception) {...), because all classes are ultimately derived from the object, catch blocks without data types must appear at the end. Generalized catch blocks are rarely used because they cannot capture any information about exceptions. Avoid exception handling to handle unexpected situations. Developers should try to avoid exceptions caused by unexpected situations or normal control flow, exceptions are designed to track exceptional, unexpected, and potentially serious consequences. Exceptions are used for the expected situations, this will make your code hard to read, understand, and maintain.

C # Some performance loss will occur when an exception is thrown. Compared with most operations, the speed is in the nanoseconds, which may cause latency in milliseconds. People usually do not pay attention to this delay, unless the exception is not handled.

 

8.Throw can be used in a catch Block: An exception can be re-thrown in a catch Block (for example, in the implementation of catch (ArgumentNullException ex), a call to throw ex can be included ), then, if an exception is re-thrown like this, the stack tracing will be reset to the re-triggered location, instead of reusing the original triggering location. In a catch Block, if you re-raise a different exception, not only will the triggering point be reset, but the original exception be hidden. In order to keep the original exception, you need to set the InnerException attribute for the new exception (this attribute can usually be assigned by the constructor ).

 

9.Custom exception: the only hard requirement for a custom exception is that it must be retrieved from the System. exception or a subclass of it is derived. In addition, when using a custom Exception, follow the best practices below.

(1) All exceptions should be suffixed with "Exception" to demonstrate its purpose.

(2) generally, all exceptions should contain the following three constructors: no parameter constructor, constructor for obtaining a string parameter, and constructor for obtaining a string and an internal exception.

(3) Avoid using a deep inheritance hierarchy (generally less than 5 levels ).

 

10.From NET Framework 4, A TryParse method is added for the enumeration type.

 

------------------------------------------- The above content is organized according to the "C # Essence of the third edition"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.