C # Advanced Programming (iii)-An explanation of objects and types

Source: Internet
Author: User

3.2 Classes and structures

The difference between a class and a struct is how they are stored in memory, how they are accessed (similar to the type of reference stored on the heap, and the type of values stored on the stack) and some of their characteristics .

Syntactically, classes are very similar to structs, and the main difference is that structs use the keyword struct instead of class to declare.

3.3 Class Members

3.3.1 Data members

A data member is a member that contains class data- fields , constants , and events .

3.3.2 Function members

Function members provide some functionality for manipulating data in classes, including methods , properties , constructors and destructors (finalizers), operators , and Indexer .


      1. Method

        The difference between ref and out:

        ref must already be initialized before it is passed, and out is not required.

        The essence of ref is to pass a value type for reference , and out is to increase the return value.

Named parameter: You can specify its name in the process of passing the parameter, in the format MethodName (parametername:value)

        Params Keyword: must be on the last side of the method parameter.

Overloading of methods: cannot differentiate only on return types, not only between declarations ref , out, or params .


      1. Property

Concept: A property is one or a pair of methods that, in the client code's view, is a field.

The get accessor takes no parameters and returns the type of the property declaration.

The set accessor takes a value parameter with the same type as the declared type.

Access modifiers for properties: In the Get and set accessors, you must have an access level with attributes.


      1. constructor function

A declaration is constructed by declaring a method that contains a similar name, but the method does not return a value.

If a constructor with parameters is provided, the compiler does not automatically provide a default constructor.

(1) Static constructors

Reason for writing a static constructor: There are static fields or properties in the class that need to be initialized from the external source before the class is first used.

. The net runtime does not make sure when to execute a static constructor, so it should not be required to execute code in a static constructor at a particular point in time. But you can be sure that it is only called once before all references.

A parameterless constructor can be defined in the same class as a static constructor.

(2) Calling other constructors from the constructor

          base and this keyword

3.3.3 Read-only fields

    The difference between readonly and const :

    readonly can be assigned to a constructor, and a const cannot be assigned to a value, only initialized.

3.4 Anonymous Types

    The var and new keywords can be used together to create anonymous types, for example.

static void Main (string[] args) 2  3  4         {5  6  7             var test = new {Name = "Earl Jones", age = 17}; 8  9 Ten             Console.WriteLine (Test. ToString ());             Console.WriteLine (Test. Name.gettype (). ToString ());             Console.WriteLine (Test. Age.gettype (). ToString ());             Console.readkey ();         Copy Code

The output results are as follows:

    

    We do not know the type of the object, the compiler has "forged" a name for it, but only the compiler can use it, and we cannot and should not use any type of reflection on the new object because it does not get a consistent result.

3.5 structure

    • Structs are value types, not reference types, whose lifecycle constraints are the same as simple data types, and the REF keyword can be used to reduce performance loss when passing structures.

    •   Structures are generally used to express simple combinations of data.

    • Structs do not support inheritance, but all structures inherit from System.ValueType, and System.ValueType inherit from System.Object.

    • Using structs, you can specify how fields are laid out in memory.

    • For structs, the compiler always provides a default parameterless constructor, which is not allowed to be replaced or provides an initial value for the field in the struct, which must be provided in the constructor.

    • The public fields in the structure are acceptable programming methods.

    • The use of the new keyword when defining a struct is simply a call to its constructor, and the declaration of the variable is actually allocating space for the structure, so the following code is not called an error.

1 mystruct mystruct/*= new MyStruct () */;2 mystruct.name = "Earl Jones"; 3 mystruct.age = 17;

  overriding structure default constructor will error :

    

3.6 Weak References

When you instantiate a class or struct in code, a strong reference is formed as long as the code references it.

The difference between strong and weak references is that a strong reference is not recycled by GC whenever a reference is available, and a weak reference can be reclaimed by the GC at any time, so it must be used to determine if it is alive. Such as:

1   MyClass MyClass; 
2 weakreference weakmyclass = new WeakReference (new MyClass ());
3 ( weakmyclass.isalive)
4 {
5 myClass = weakmyclass.target as MyClass;
6 Console.WriteLine (myclass.value );
7

3.7 Parts Category

The partial keyword allows you to put a class, struct, method, or structure in multiple files.

If the declaration resembles the following keyword, these keywords must be applied to all parts of the same class:

    • Access modifiers

    • Abstract

    • Sealed

    • New

    • General constraints

3.9 Object class

All classes inherit from the System.Object class.

Method:

    • ToString ();

    • GetHashCode ();

    • Equals (); Here are three comparisons of three methods for comparing object equality.

    • Finalize ();

    • GetType ();

    • Gmemberwiseclone ();

3.10 Extension methods

Extension methods are used to add methods in some classes that cannot be directly modified in the source code.


 1 using System; 2 3 Namespace extension method 4 {5 class program 6 {7 static                     void Main (string[] args) 8 {9 MyClass myClass1 = new MyClass (); 10 Myclass1.sayhitosomeone (); Myclass1.sayhi (); Console.readkey ();  (+)-Class MyClass         void Sayhi () {Console.WriteLine ("I am the most primitive method"); 21}22}23 Static class AddMyClass25 {$ static public void Sayhitosomeone (this MyClass MyClass) {Console.WriteLine ("I am an extension method");}30 s            tatic public void Sayhi (this MyClass MyClass) ("I am the extension method Console.WriteLine"), 34  }35}36} 

  Results of the output:

  

  From the above:

    • The extension method must be defined in a static class.

    • The first parameter of the extension method is the class that is placed after this, and this method is part of the class.

    • That is, the extension method is a static method, and it is called by the syntax of the calling instance method.

    • If the extension method has the same name as a method in the class, the extension method is never called.

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.