Java attack C #-Improvement of grammar knowledge points,

Source: Internet
Author: User

Java attack C #-Improvement of grammar knowledge points,

Summary of this Chapter

In the previous chapter, we talked about the differences between object-oriented ideology C # and JAVA. The author starts with three main characteristics of object-oriented. This chapter focuses on some knowledge points for C # improvement. There are many new knowledge points after. NET Framework 2.0. These knowledge points make C # more diversified in writing. Some of the statements really make the author feel very good. This part of knowledge is more unique to C. It is very difficult to use JAVA knowledge. So this chapter may be pure C. Although many features have emerged in JAVA 7 and JAVA 8. Unfortunately, I did not seriously learn new features.

Improved initialization syntax

I. class initialization method.Class initialization, added the attribute initialization function. The following code.

Previous:

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

New:

Person person = new Child () {Sex = "male", Name = "Aomi"}; person. Move ();

II,Collection class initialization method. The initialization of the Collection class is not a monotonous method. You can add some values during initialization.

Previous:

List<string> strList = new List<string>();strList.Add("a");strList.Add("b");strList.Add("c");

New

List<string> strList = new List<string>() { "a", "b", "c" };
Introduction of the keyword var

In the previous chapters, we often use strong types. If you have used Javascript, you should understand the weak type and strong type. To put it simply, the weak type is hard to determine when the type is defined. You can only know what type it is when running it. C # is a strongly typed language. That is to say, you must know what type of data is defined during compilation. However, C # makes the author not understand this point. Why? Let's take a look at the code below.

var local = 1;

This code is a definition ...... Okay. I do not know what to say. This is the case with relevant information. It is not of no type. It is not a var type either. However, during compilation, the system will determine what type it is. It is determined that the above Code is of the int type during compilation. As shown below

The prompt in the above image is not displayed. It is a local variable int local. It is clearly indicated that it is an int type. During the development process, I have never encountered the need to use the var keyword to declare variables. So I have never understood it-When will it be used. Pay attention to the syntax here. C # is a strongly typed language. Therefore, the var keyword must be set to an initialized value when defined.

Due to the introduction of the var keyword, a statement of the Declaration class is also displayed. Many books call them anonymous. The following code

var student = new  {     Name="aomi",    SNO="s0001"};
Introduction of keyword dynamic

As mentioned above, C # is a strong language. The introduction of the keyword var is really hard to understand. If the author says that he is a weak type, it seems that he is different from C. If it is a strong type, and there is no var type. I don't understand it. This may be the reason C # introduced the keyword dynamic in 4.0. There is a brand new concept called dynamic type. So what is a dynamic type? Let's take a look at the sub-types that will appear during compilation based on the same method as the above keyword var. Lower

It seems that it is still the dynamic type during compilation. It seems that there are real dynamic types. Of course, this is not the case. Let's take a look at his running status. Let's take a look at how visual studio is debugged.

Set the breakpoint first. As long as you click the top left of the writer (where the code is written), a red dot will appear. That is the breakpoint. Eclipse seems to have right-click and select set breakpoint. Unfortunately, visual studio does not. You only need to right-click the settings breakpoint in the area where you write code. Please try it on your own.

After the breakpoint is set successfully, start the (Debug mode) code. At this time, we can monitor the variables to be viewed. Right-click the corresponding variable. As follows:

When you click "add monitoring (W)", the corresponding monitoring form is displayed. The following figure shows how to pull the corresponding form.

Okay. The next step is how to let him perform the next step. On the top of visual studio, the tool for the following image is displayed.

F5: Start

F10: next step. It is equivalent to F5 of eclipse.

F11: Internal code. It is equivalent to F6 of eclipse.

Shift + F11: jump out. It is equivalent to F7 of eclipse.

Okay. I believe everyone should be able to debug it. Let's go to the topic. From the above monitoring form, we can see the status of the variable student. Type: dynamic {int }. In this way, we can understand. The dynamic type is determined during running.

The keyword dynamic is different from the keyword var because the dynamic type exists. Therefore, Initialization is not required during definition. The corresponding type can be further determined during running. Try it.

C #:

Dynamic student = 1l; if (student is int) {Console. writeLine ("int type");} else if (student is long) {Console. writeLine ("long type ");}
Parameter Changes

We all know that there are no default values for earlier methods. In addition, values must be passed in the defined order. C # Some changes have been made here.

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

We can see the above changes in the parameter string B = "bbb" in the Generation segment. This means that when the mothed method is called, the value of parameter B is not required. It uses the default value bbb. But parameter a must be passed. The Code is as follows:

First usage: The parameter value is the default value (bbb ).

 mothed("aaa");

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

mothed("aaa","ccc");

Third usage: this is a new usage. You don't have to worry about the sequence.

mothed(b:"ccc",a:"a");
Method changes

Both JAVA and C # have the concept of defining events. So what is C # Like to define an event?

1. Use the keyword delegate to declare the delegate type of the event. That is, what is the structure used to indicate future events. If you want to return the type. The parameter type. There are several parameters. These can be defined by developers themselves. Including the name of the delegate type.

 public delegate void MoveHandler(object obj);

Note that the above Code can store a separate cs file. It is the same as the class code storage level.

2. After the delegate type is defined, we can declare the corresponding event based on the delegate type. The keyword "event" indicates the current event. Then, trigger the corresponding event in the Move method. Determine whether 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)                ChildMoveHandler(this);        }    }

3. With the above Code Declaration, we can try the C # event. The following code. Before the child variable calls the Move method. The author initializes an event for him. At this time, he is calling the Move method. When judging that the event is not empty, he passes the event as a parameter. In the following Event code (Child_ChildMoveHandler method), the corresponding obj is converted to a variable of the Child class through the as function. Print the name. Be sure to use "+ =" when assigning values to events ". That is, adding events is not assigning values. Conversely, "-=" indicates the deletion 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);        }            }

The above three steps are previous usage. Now we have a new usage. The keyword Action usage is introduced. Simply put, the method is passed. Previously, only variables or objects can be passed. Now the method can be passed. Event declaration becomes 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 usage method remains unchanged. 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);        }            }

See. The definition of events becomes simple. Only the usage of Action. I may not understand it at all. What does Action <T in> mean? It is easy to say that Action can implement method transfer. It is a pity that only the type and number of parameters can be controlled, but the return type cannot be controlled. The return type can only be void. If you want to control the returned type, use another keyword Func. At this time, you can control the return type. You 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);        }    }

Run the 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);        }            }

Obviously, both the Action keyword and the Func keyword are the operations on the method. However, the event declaration is more readable and simple. At least do not declare the delegate type in writing. Since the operation on the method. Can this be the case? Action and Func can be defined as member variables within 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");        }    }

Let's see how to execute the 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 very important that the above events use "+ =", and now "= ". That is, the meaning of the value assignment.

We can see that C # is converting the method into a usable variable. Because of this, there are two ways to write the value assignment method. Let's take a look.

1. assign values to the 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();        }    }

2. assign values to lambda expressions.

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();        }            }
Summary

This chapter focuses on some new features introduced by C # syntax. Some of them are worth our attention. The action and func used for the special event declaration. The second is the parameter changes. This is often used in the development process.

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.