"C # Advanced Programming", "Chapter III" Objects and types--learning notes

Source: Internet
Author: User

After seeing C + +, it is not difficult to look at the object-oriented sense of C #, but there are some differences.

1. Class definition

Use The class keyword to declare a class, which differs from C + + in that it does not require a colon after curly braces

Class class Name {    //Inside of class}//c++ here is a colon, and C # has no

2. Class Members

3. Fields and properties

First, let's distinguish between the fields, constants, and event members in C # data members. Fields, constants are related variables to the class. An event is a member of a class that allows an object to notify the caller when certain behaviors occur, such as changing a field or property of a class, or doing some form of user interaction.

So now we're going to look at the fields and properties, the properties are defined as follows:

[Access Rights] Type [Property name] {    //get and set pre-access properties default to public    get    {        return [field corresponding to this property];    }    Set    {        //Do what you want to do with the field    }}

Let's take a look at the example of how get and set works by the way

"C #"

Class test{    private int num;    public int num    {public        get        {            return Num;        }        Public set        {            num = value;}}    }

"C + +"

Class test{    private int num;    public int Getnum ()    {        return num;    }    public void Setnum (int value)    {        num = value;    }}

I don't know if you found out. In C #, the Getnum function is made into a get,setnum set, and the value of the set is saved with value. In fact, a property is a way to read and assign a field to an operation. However, the parentheses after the method name are not required when calling. Take the code above as an example: Test.num. You can call him as long as it's done.

4. Methods

In fact, this and is a member function, but in C # the scope of member functions is broader. Now let's see.

Definition of the <1> method

[Access Properties] [Return value type] Method name ([parameter]) {    //method Internal implementation}

As an example:

Class test{    private int A, B;    public int Add ()    {        return a + B;    }}

<2> Call Method:

Using System;namespace myfirstprogram{    class program    {        class Test        {            private int, a, b;            public int Add ()            {                return a + b;            }        }        static void Main ()        {            Test p = new Test ();            P.add (); The call to the method}}}    

<3> passing parameters to methods

This is the same as the normal function pass parameter. In C #, it is particularly important to note that, unless specifically declared, reference types are reference passes and value types are value-passing.

<4> Optional Parameters

In fact, this is the default value in C + +

<5> ref and Out parameters

The type of value passing is the default, but sometimes we need to change it. Then there is ref and out.

public void Add (ref int b) {    b++;}

You also need to add the REF keyword when calling

P.add (ref i);

In fact, this is the same as the reference mechanism in C + +, but, in C #, ref must use a variable that has been assigned a value. However, when out is prefixed, the variable can be uninitialized.

Special note: Ref and Out parameters cannot have default values:

public void Add (ref int b = 2)  //error, default value, cannot be ref or out{    b++;}

<6> unordered Delivery

This mechanism is not in C + +. But it doesn't seem to work.

function String SetName (string fname,string LName) {    return FName + "" + LName;} Normal call SetName ("John", "Doe");//Unordered call SetName (LName: "Doe", FName: "John");
The results of the two invocations are consistent.

5. Constructor function

Constructors are methods that initialize object data when an object is created. Its method name is the same as the class name, and there is no return type. If not written, the compiler automatically creates an parameterless constructor that initializes all data to the standard default values.

Class test{    //As long as the parameterless constructor is created, the background will not automatically generate the constructor public    Test ()     {        //constructor Implementation    }    //override constructor    public Test (int number)    {        //constructor internal implementation    }}

Another feature of C # is the ability to write parameterless constructors to a class, and the reason for writing a static constructor is that there are static fields and properties inside the class that need to be initialized before the class is first used. Note: Static constructors run at most one time.

6. Anonymous Type

Declared by the keyword VAR, its implicitly typed variable. In fact, I think this is equivalent to a class without a name. It's not a good feeling, so use it with caution. The statement reads as follows:

If an object contains a person's name.

var person = new {FirstName = "John", LastName = "Doe"};

7. Partial class

You can use the partial keyword to put a class, struct method, or excuse in multiple files, usually a class in a file, but at the time of multi-person development You can show the power of the partial.

8. Weak references

This mechanism is designed to conserve memory. Because when a program instantiates a class or struct, a strong reference (relative to a weak reference) is formed as long as there is a code reference. If this class is very large and not frequently accessed. Then a lot of memory is wasted, so the concept of weak references is introduced. Weak references are created using the WeakReference class. Because an object can be recycled at any time, you must first confirm its existence when referencing the object.

static void Main () {    WeakReference testreference = new WeakReference (new Test ());    Test tmp;    The purpose of IsAlive this property is that the Testreference object is recycled without the    if (testreference.isalive)    {        ///If the class object exists, then reference the object        tmp = Testreference.target as Test;    }}

9. Static Class

Static methods and properties are used internally only by static classes. A static class is functionally the same as a class created using a private static constructor. Note: Static classes cannot create instances.

Conversely, we can use the static keyword to check if an instance of the class is created, and if it is the compiler will error.

10. The difference between class and structure (struct)

The ① class can inherit, however the structure cannot

The ② class is stored on the managed heap, but the structure is stored on the stack (so the structure is more efficient than the class )

The ③ class is a reference type, whereas a struct is a value type

The default parameterless constructor for the ④ principle structure is not replaceable, but if the non-parametric constructor override is assigned to all data members, you can override

11. The difference between a read-only field and a constant

The read-only attribute has a readonly declaration. The concept of a constant is to include a variable that cannot be modified. But sometimes it takes some variables whose value cannot be changed, but is unknown before running. So we introduced a read-only attribute. Read-only properties are much more flexible than const, and ReadOnly can be assigned to them in a constructor, so that each instance can have a different value.

12, the use of typeof

typeof can get the object type,

Type t = typeof (int); Console.WriteLine (T.name);
This will output Int32.

13. Use of using

Using in C # is the same as a typedef of C + +:

Using Print = system.console;namespace myfirstprogram{    class program    {                static void Main ()        {            Print.writeline ("Hello world!");}}}    

The third chapter is about the same thing.



"C # Advanced Programming", "Chapter III" Objects and types--learning notes

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.