[C #] C # learning notes-indexer, pointer type, implicit type, extension method, partial method, anonymous type

Source: Internet
Author: User
Tags define abstract define null

C # learning notes-indexer, pointer type, implicit type, extension method, partial method, anonymous type

Luo chaohui (http://www.cnblogs.com/kesalin)

C # And. Net advancedProgramDesign Reading Notes

Indexer, pointer type 

1. You can use the indexer method this [type Param] to customize a type of indexer. C # The Compiler creates an attribute named item for the indexer method to map the correct method for obtaining/setting. Example:

 
PublicPersonThis[IntIndex]
{
Get{Return(Person) list [Index];
Set{List. insert (index, value );
}

2. The indexer method can be overloaded. You can also implement a multi-dimensional indexer or define the indexer in the interface.

3. Operator Overloading: [], (), and the abbreviated value assignment operator (+ =,-=, and so on) cannot be overloaded. True and flase can also be used as operators. In C #, if a type overload related binary operators, the abbreviated value assignment operator automatically has corresponding new functions. Similarly, we also need to reload the pre-increment ++ or pre-increment -- to automatically obtain the post-increment or post-increment functions. In C #, The = operator must be reloaded at the same time! = Operator (if this is not done, the compiler will prompt). This rule applies to comparison-Based Operators (>,<,>=,<= ). The overload operators are expressed internally by hiding them. For example, op_addition () and op_equality. We can also call these static hiding methods in other languages that do not support overload operators.

4. C # also supports custom conversions. The conversion method must be static. For example, convert rectangle to square. Like heavy-duty operators, methods that contain implicit or explicit keywords correspond to specialized commands op_implicit and op_explicit respectively in the pencil.

 
Public Static Explicit OperatorSquare (rectangle R)
{
Square S;
S. Length = R. height;
ReturnS;
}

5. C # also supports the original pointer type and related pointer operations. We should specify the/unsafe settings of the compiler to support insecure encoding. We use the unsafe keyword to specifically declareCodeBlocks (including structures, classes, type members or parameters) are insecure code. The following keywords are used for unsafe encoding: stackalloc (allocates memory directly from the call stack), fixed (used to fix the address of the reference type variable in the insecure context memory, in this way, the garbage collector will not reset the address of the variable during execution) and sizeof.

6. Preprocessing commands: there are no independent preprocessing steps in C #, but preprocessing commands are processed in the lexical analysis phase of the compiler. In addition to the traditional # define, # If series, C # also adds the # region, # endregion preprocessing command used to mark the code block.

Implicit type

7. var keyword (to be accurate, VaR is not a keyword. We can declare a variable named var, a parameter or a field without the compiler reporting an error ): we can use VaR to replace the formal data type name for local variables, parameters and fields. The compiler will deduce the Data Type of the variable based on the initial value used to initialize the local variable. Implicit local variables are strongly typed data. For example:

Static VoidDeclareimplicitvars ()
{
VaRMyint =0;
VaRMybool =True;
VaRMystring ="It's a string";
}

When using VAR to define an implicit local array, the array members in the array initialization must be of the same inferred type. Implicit local variables are not set to system. object by default.

 
VaRD =New[] {1,10,100,100};

8. There are some restrictions on using VAR: first, explicit types can only be applied to declarations of methods or local variables in properties, and VAR cannot be used to define return values, data members of the parameter type or type. Secondly, the local variables declared by VAR must be assigned a value at the same time during the declaration, and cannot use null as the initial value. Again, do not use C? Identifier to define null and implicit local variables.

9. Functions of implicit local variables: the query expression is used by the LINQ technology. It can dynamically create a result set based on the Query format, so that we can use VaR, therefore, you do not need to explicitly define the types that may be returned by the query.

Automatic attributes

10. Automatic attributes: to simplify the Data encapsulation process of simple fields, C #3.0 provides the automatic attribute syntax, this feature allows us to use the new syntax to define supported fields and related C # attributes for the compiler. If you want to define abstract attributes, you also need to use abstract keywords. Note: To define automatic attributes, you must provide read and write functions. We cannot create read-only or write-only automatic attributes. Example:

 
ClassCar
{
PublicSting name {Get; ProtectedSet;};
}

Extension Method

In 11, C #3.0, we can define a method as an extension method. Simply put, the extension method allows existing compiled types (such as classes, structures, interfaces) and the types to be compiled (such as the types that contain extension methods) obtain function extensions without being directly updated. In this way, we can add functions for the pre-compiled type (or even the code we don't have) through the extension method, and these methods will be separately stored.

12. There are some restrictions on using the extension method: first, the extension method must be static; second, all extension methods must use the keyword "this" to modify the first parameter (and only the first parameter). Third, each extension method can only be called by the correct instance in the memory, or it is called through its static class. Example: This extension allows system. int32 to invert its own values.

 
Static ClassMyextensions
{
Public Static IntReversedigits (This IntI)
{
Char[] Digits = I. tostring (). tochararray ();
Array. Reverse (digits );
StringNewdigits =New String(Digits );
Return Int. Parse (newdigits );
}
}

13. Behind the use of extension methods, the compiler only calls static methods in a common way, that is, the variable that calls the method is used as the call parameter (that is, this ). In the preceding example, the compiler converts the code to myextensions. reversedigits (aint). Therefore, we can use the common C # syntax to call the extension method as if we call a common static method.

14. Due to the static nature of the extension method, we cannot directly access members of the extension type in the extension method, but we can use this to extend the type of public members (only public members ).

15. Scope of the Extension Method: Put the static type containing the extension method into an independent namespace, other Namespaces in the same assembly can use the standard C # keyword using to import these static types and the extension methods they contain. Note that if you do not explicitly import the correct namespace, the extension method is unavailable to the current C # code file.

16. Microsoft recommends placing the Extension Method in an independent assembly (independent namespace)-extension library to facilitate code modularization and management. We can not only extend the class but also extend the interface. The extension interface is a little special. When we extend an interface to make it have new members, we must provide the implementation of these members, this seems to be out of the essence of the interface type (in fact, all types implement static new member implementations ).

Division Method (partial)

17. We can use the partial keyword to construct the Division class definition, so that we can implement the type syntax across multiple code files, only each division type has the same fully qualified name. From C #3.0, we can apply partial to the method level, which allows us to build a method prototype in one file and implement it in another file, but there are many restrictions on doing so. First, the partial method can only be defined in the partial class. Second, the partial method must return void. Third, the partial method can be static or instance-level. Fourth, the partial method can have parameters (including parameters modified by this, ref, or Params, but not out modifiers). Fifth, the partial method is always implicitly private. Sixth, the partial method may be placed in the compiled assembly or not, because the compiler determines whether the method should be put into the Assembly based on whether the method body is implemented. If there is no method body, therefore, the trace of method usage (call, metadata description, and prototype) will be removed during compilation.

18. Because the partial method must be implicitly private and always returns void, the use of the partial method is not large. By using the partial modifier to mark the syntax, the builders of other classes can choose to provide implementation details. In this way, the division method provides a simpler solution than using preprocessing commands, provides virtual implementation for virtual methods or throws notimplementexception exceptions. In addition, it is common to use the division method to define lightweight events, which allows class designers to provide method hooks, just like event handlers, developers can choose whether to respond to an event or not. According to the naming conventions, such lightweight event handling methods use the on prefix.

Initialization

19. The object initializer is implemented from left to right. For containers, we can use the set initialization syntax, which allows us to initialize containers like initializing normal arrays.

Anonymous type

20. The anonymous type is a natural extension of the anonymous method. When defining an anonymous type, you need to use the new keyword VaR and the object initialization syntax described earlier. For example:

  static   void  main ( string  [] ARGs) 
{< br> /// construct an anonymous object to represent a car
var mycar = New {color = " White " , make = " Saab " , currentspeed = 60 };
console. writeline ( " >> my car is a {0} {1 }. ", mycar. color, mycar. make);
}

21. All anonymous types automatically inherit system. Object. Therefore, they all support every member of the base class. Therefore, we can call methods such as GetType () and tostring () on them. The type name of an anonymous class is determined by the compiler, each name/value pair defined by the object initialization syntax is mapped to an attribute with the same name and a private data member encapsulated by this attribute. Equals () is a value-based semantics that compares the values of each data member of two objects, however, the anonymous type does not overload the equal operators (= and!) of C! =), So the equal operator is based on the comparison reference.

22. usage of the anonymous type: Use the anonymous type with caution, especially when using the LINQ Technology (quickly build an object without defining its functions ). There are many restrictions on the anonymous type: First, you cannot control the name of the anonymous type; second, the anonymous type inherits from system. object; third, events, custom methods, custom operators, and custom rewriting are not supported for the anonymous type; fourth, the anonymous type is implicitly closed (sealed); fifth, only the default constructor is used to create an anonymous instance.

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.