Improvement of knowledge points of Java attack c#--grammar

Source: Internet
Author: User

This chapter is a brief statement

In the previous chapter we talked about the differences between object-oriented thinking C # and Java. The author starts with the three main characteristics of object-oriented. And this chapter mainly talk about some C # improved knowledge points. Many new knowledge points appear after the. NET Framework 2.0. These points of knowledge make C # more diverse in its wording. Some of the writing has really made the author feel very good. Because this part of the knowledge is more unique to C #. It is difficult to use the knowledge of Java side. So this chapter may be pure C #. Although there are many features in Java 7 and Java 8. Unfortunately, I did not seriously study the new features.

Improvements to initialization syntax

first, the initialization of the class. the Initialization property value function is added when the class is initialized. The following code.

Previous:

  Person person = new Child ();  Person. Name = "Aomi";  Person. Move ();

NEW:

Person man = new Child () {    Sex = ' Male ',    Name = ' Aomi '}; Move ();

Second, the initialization of the collection class mode . The initialization of the collection class is not the same as in the previous monotone way. It is possible to add some values together at initialization time.

Previous:

list<string> strlist = new list<string> () Strlist.add ("a"); Strlist.add ("B"); Strlist.add ("C");

The new

list<string> strlist = new list<string> () {"A", "B", "C"};
Introduction of the keyword VAR

The types we often use in the previous chapters are strongly typed. If you've ever worked with JavaScript, you should know about weak types and strong types. The simple point is that a weak type is a type that is difficult to determine when defined. Only when you run it will you know what type of man he is. C # is a strongly typed language, meaning that you must know what type of data is defined at compile time. However, C # in this point makes the author very not understand. Why do you say that? Take a look at the following section of code.

var local = 1;

This piece of code is a definition of a ... All right. I'm not sure what to say. There is the relevant information is said in this way. He is not without type. Nor is it a var type. But when compiling, it will determine what type he is. That is, when the code above compiles, it is determined that he is of type int. As in the picture below

See the above picture inside the hint is not. He is a local variable int local. It is clear that he is an int type. In the process of development, I have not encountered the need to use the VAR keyword to declare variables. So the author's heart has always not understood-this exactly when to use AH. This place has a bit of grammar to pay attention to. Just now, C # is a strongly typed language. So the Var keyword must give the value initialized when it is defined.

As a result of the introduction of the Var keyword, a declarative class is also presented. Many books call them anonymous types. The following code

var student = new  {     name= "Aomi",    sno= "s0001"};
Introduction of the keyword dynamic

I mentioned above that C # is a strong type of language. The introduction of the keyword VAR is really hard to understand. If I say that he is a weak type, it seems to have a wrong with C #. If he is a strong type and does not have the Var type. I do not understand the author. Maybe that's why C # introduced the keyword dynamic at 4.0. There is a new concept called dynamic type. So what is a dynamic type? Let's take a look at what kind of type it will be when compiling it, just like the keyword var above. Under

It seems to be a dynamic type at compile time. It looks like there's a real dynamic type. Of course, this is not the way to turn. We'll also look at the way he runs. Take a look at how Visual Studio is debugged.

Set breakpoints first. Red dots can appear as long as the writer (that is, where the code is written) is clicked on the far left. That's the breakpoint. Eclipse seems to have a right click in the Select Set breakpoint. Unfortunately, Visual Studio does not, only the area where you write code right-click Set Breakpoints. Please try the readers on their own.

After the breakpoint is set successfully, start the (debug mode) code. At this point we can monitor the variables to be viewed. Select the corresponding variable to right-click. As follows

When you click "Add Monitoring (W)", the corresponding monitoring form will pop up. The following is the author to pull out the corresponding form.

All right. The next step is to get him to do the next steps. At the top of Visual Studio, the tool button for the picture below appears.

F5: Start

F10: Next. Equivalent to Eclipse's F5.

F11: Make internal code. Equivalent to Eclipse's F6.

SHIFT+F11: Jump out. Equivalent to Eclipse's F7.

All right. I believe we should be able to debug it. Let's get down to the chase. From the monitoring form above we can see the variable student state. The type is Dynamic{int}. This way we can understand. A dynamic type is a type that is determined at run time.

The keyword dynamic is not the same as the keyword Var because there is really a dynamic type. So you don't have to initialize when you define it. The type that he corresponds to can be further determined at run time. Let's not bother to try.

C#:

Dynamic student = 1l;if (student is int) {     Console.WriteLine ("type int");} else if (student is long) {    Console.WriteLine ("Long Type");}
Change of parameters

We all know that the early methods are not corresponding to the default values. The values must be passed in the order defined. C # has made some changes here.

public static void Mothed (string a,string b = "bbb") {}

We can see the change of the parameter string b = "BBB" above in the generational section. This means that when you call mothed this method, you can not pass a value to parameter B. He will use the default value: BBB. However, parameter a must be passed. The code is as follows

The first usage: the value at this time is the default value (BBB).

Mothed ("AAA");

Second use: This is the same as the previous usage.

Mothed ("AAA", "CCC");

The third usage: This new is a usage. No, of course, the problem of order.

Mothed (b: "CCC", A: "a");
The change in method

Either Java or C # has the concept of defining events. So what does C # look like to define an event?

1. First use the keyword delegate to declare the delegate type of the event. That is, the structure that represents the future event to occur. If you want to return what type. The type of argument that will be passed in. There are several parameters. These can all be defined by the developer themselves. Includes the name of the delegate type.

public delegate void Movehandler (object obj);

Note that the above code can be a separate CS file to store him. The same level as the class code.

2. Once the delegate type is defined, we can declare the corresponding event based on the delegate type. The keyword event is meant to indicate the current event. The corresponding event is then triggered in the Move method. Determine if the event is empty. If not, the event is triggered.

C#:

public class Child:person    {public        event Movehandler Childmovehandler;        Public Child ()            : Base ("Aomi")        {         } public        override void Move ()        {            if (childmovehandler! = null) C9/>childmovehandler (this);        }    }

3. With the declaration of the above code, we can try out the C # event. As in the following code. Before the child variable calls the Move method. The author will give him an initialization of an event. At this point, he calls the Move method, judging that the event is not empty and passes itself to the event as a parameter. The following event code (the Child_childmovehandler method) converts the corresponding obj into the child class by using the AS function. In print out the name to come. Be sure to use "+ =" when assigning a value to an event. That is, the increment event is not an assignment. The opposite of "-=" indicates a delete event.

C#:

Class program    {        static void Main (string[] args)        {child child            = new Child ();            Child. Childmovehandler + = Child_childmovehandler;            Child. Move ();        }        public static void Child_childmovehandler (Object obj)        {child            src = obj as child;            Console.WriteLine (src. Name);        }            }

For the above three steps is the previous usage. Now there's a new usage. Introduced the use of the keyword action. Simply speaking, the method is passed. Previously, only variables or objects could be passed. Now the method can also be passed. The event declaration becomes very simple.

C#:

public class Child:person    {public        event Movehandler Childmovehandler;        public event action<object> Childactionmovehandler;        Public Child ()            : Base ("Aomi")        {         } public        override void Move ()        {            if (childmovehandler! = NULL)                Childmovehandler (this);            if (this. Childactionmovehandler! = null) this                . Childactionmovehandler (this);        }    }

The way you use it is still not becoming. The following code

    Class program    {        static void Main (string[] args)        {child child            = new Child ();            Child. Childmovehandler + = Child_childmovehandler;            Child. Childactionmovehandler + = Child_childactionmovehandler;            Child. Move ();        }        public static void Child_childactionmovehandler (Object obj)        {child            src = obj as child;            Console.WriteLine (src. Name);        }        public static void Child_childmovehandler (Object obj)        {child            src = obj as child;            Console.WriteLine (src. Name);        }            }

Let's see. The definition of the event has become very simple. Just for the use of action. Maybe it's a little bit out of the picture. Action<t in > What does this mean? It's easy to say that action can pass the method. Unfortunately, only the type and number of parameters can be controlled, but the return type cannot be controlled. It is also said that the return type can only be a void type. Then control the type of return, I'm sorry please use another keyword func instead. The return type can be controlled at this time. Just cannot use void as the return type. The code is as follows.

  public class Child:person    {public        event Movehandler Childmovehandler;        public event func<object,int> Childfuncmovehandler;        Public Child ()            : Base ("Aomi")        {         } public        override void Move ()        {            if (childmovehandler! = null)                Childmovehandler (this);            if (this. Childfuncmovehandler! = null) this                . Childfuncmovehandler (this);        }    }

Execute code:

Class program    {        static void Main (string[] args)        {child child            = new Child ();            Child. Childmovehandler + = Child_childmovehandler;            Child. Childfuncmovehandler + = Child_childfuncmovehandler;            Child. Move ();        }        public static int Child_childfuncmovehandler (object obj)        {child            src = obj as child;            Console.WriteLine (src. Name);            return 0;        }        public static void Child_childmovehandler (Object obj)        {child            src = obj as child;            Console.WriteLine (src. Name);        }            }

It is clear that both the Action keyword and the Func keyword are operations on the method. But the statement of the event became more readable and simple. At least you don't have to write the declaration delegate type. Since the operation of the method. Is that possible? The action and Func can be defined as member variables inside a class. Of course.

public class mothed    {public        func<string, int> printfunc;        Public action<string> printaction;        public void Execute ()        {this            . Printfunc ("Printfunc Aomi");            This. Printaction ("Printaction Aomi");        }    }

Look at the execution code.

   Class program    {        static void Main (string[] args)        {            mothed mothed = new mothed ();            Mothed. Printaction = printaction;            Mothed. Printfunc = Printfunc;            Mothed. Execute ();        }        public static int Printfunc (string value)        {            Console.WriteLine (value);            return 0;        }        public static void Printaction (string value)        {            Console.WriteLine (value);        }    }

It is important to note that the above event is with "+ =" and is now used "=". That is the meaning of the assignment.

We can see that C # is turning the method into a variable that can be used. Because of this, there are two ways to approach the assignment of a method. Let's take a look at it.

1. Assign a value to an anonymous method.

  Class program    {        static void Main (string[] args)        {            mothed mothed = new mothed ();            Mothed. Printaction = Delegate (string value)            {                Console.WriteLine (value);            };            Mothed. Printfunc = Delegate (string value)            {                Console.WriteLine (value);                return 0;            };             Mothed. Execute ();        }    }

The 2.LAMBDA expression is assigned a value.

Class program    {        static void Main (string[] args)        {            mothed mothed = new mothed ();            Mothed. Printaction = (String value) = =            {                Console.WriteLine (value);            };            Mothed. Printfunc = (String value) = =            {                Console.WriteLine (value);                return 0;            };             Mothed. Execute ();        }            }
This chapter summarizes

This chapter focuses on some of the new features that C # has introduced in syntax. Some of them are worthy of our attention. Action and Func for special event declarations. The second is the change in the parameters. This author is also often used in the development process.

Improvement of knowledge points of Java attack c#--grammar

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.