Comparatively learn C# basic grammar on the basis of Java

For learning a new language, the key is to learn the difference between the new language and the previously mastered language, but don't let the things in the previous language fix your own thinking mode, and look at the programming ideas of the new language.
Both Java and C# are object-oriented languages, and they are very similar. Let's learn C# in a comparative way.
insert image description here

1. Lead package

  using System;  //java用import

Second, the constructor

Same syntax as java

public class Student
{
    
    
	public Student(){
    
    
		
	}
}

3. Destructor

Similar to the constructor, the destructor (also called "finalizer") in C# is also a special member function in the class, which is mainly used to perform some necessary cleanup operations when the garbage collector reclaims the class instance.
Variables and class objects have a life cycle, and when the life cycle ends, these variables and objects will be revoked.
When an object of a class is destroyed, the destructor is called automatically. Some aftermath work can be done in the destructor.

The name of the destructor is also the same as the class name, but it needs to be prefixed with a tilde ~ in front of the name, with no return type and no parameters. As follows:

class Car
{
    
    
	~Car()  // 析构函数
	{
    
    

	}
}

The class destructor in C# cannot be called explicitly, it is called automatically when the garbage collector destroys unused objects.

4. C# data types

From a broad perspective, the data types of the C# language can be divided into three types: value types, reference types, pointer types, and pointer types are only used in non-safe code.
C# runs in the CLR, which has an automatic garbage collector, similar to java

1. Value type
Simple type:

  • Numerical types: integer type, character type (char), floating point type and decimal type (decimal)
  • Boolean type (bool)

(1) Simple types are also structural types, so there are constructors, data members, methods, attributes, etc.; therefore, the
following statement int i=int.MaxValue; string s=i.ToString() is correct;
even if it is a constant, C# also An instance of the structure type will be generated, so the method of the structure type can also be used,
for example: string s=13.ToString() is correct.
(2)

reserved word Names in the System namespace Bytes Ranges
sbyte System.Sbyte1 1 -128~127
byte System.Byte 1 0~255
short System.Int16 2 -32768~32767
ushort System.UInt16 2 0~65535
int System.Int32 4 -2147483648~2147483647
uint System.UInt32 4 0~4292967295
long System.Int64 8 -9223372036854775808~9223372036854775808
head System.UInt64 8 0~18446744073709551615
char System.Char 2 0~65535
float System.Single 4 3.4E-38~3.4E+38
double System.Double 8 1.7E-308~1.7E+308
bool System.Boolean (true,false)
decimal System.Decimal 16 ±1.0 × 10?28 to ±7.9 × 1028

(1) The decimal type is used to represent high-precision floating-point numbers, which can be used in financial related fields.
(2) Floating-point numbers have the problem of loss of precision, just pay attention to it when operating.
(3) The character type adopts the Unicode character set, and the length of a Unicode standard character is 16 bits.
(4) The integer type cannot be implicitly converted to a character type (char). Unlike java, it must be converted or expressed in Unicode. (
5) The Boolean type has two values: false and true. It cannot be considered that the integer 0 is false and other values ​​are true.
bool x=1 is wrong, there is no such way of writing, it can only be written as x=true or x=false

Struct types (Struct types)
(1) Struct types, like classes, can declare constructors, data members, methods, attributes, etc.
(2) The most fundamental difference between structures and classes is that structures are value types and classes are reference types.
(3) Unlike a class, a structure cannot be derived from another structure or class, nor can it be inherited, so an abstract structure cannot be defined, and
structure members cannot be modified by the access control word protected, nor can virtual and abstract be used to modify structure methods .
(4) A destructor cannot be defined in a structure.
(5) Although a structure cannot be derived from a class and a structure, a structure can inherit an interface, and the method of a structure inheriting an interface is basically the same as that of a class inheriting an interface.
example:

using System;
//结构定义
struct point{
    
    
	public int x,y;//结构中也可以声明构造函数和方法,变量不能赋初值
}
class Test{
    
    
	static void Main(){
    
    
		point P1;
		P1.x=166;
		P1.y=111;
		point P2;
		P2=P1;//值传递,使P2.x=166,P2.y=111
		point P3 = new point();//用new生成结构变量P3,P3仍为值类型变量
//用new生成结构变量P3仅表示调用默认构造函数,使x=y==0。
	}
}

Enumeration types (Enumeration types)
The usage of C# enumeration types is basically the same as the enumeration types in C and C++, and it is quite different from java
(1) Define enumeration

//设置初值,从1开始
enum Days {
    
    Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
//位设置初值,从0开始  
enum Days {
    
    Sat, Sun, Mon, Tue, Wed, Thu, Fri};

(2) Use enumeration

 Days day=Days.Tue;
int x=(int)Days.Tue;

(3) Different from C and C++, the C# enumeration element type can be byte, sbyte, short, ushort, int, uint, long and ulong, but not char type

   enum Days:byte{
    
    Sun,Mon,Tue,Wed,Thu,Fri,Sat};//元素为字节类型

The initial value of the variable: the initial value of the general simple type is 0, the Boolean type is false, and the reference type is null.

For complex structure types, it is too troublesome to assign values ​​to each data member in this way.
Since the numerical types are all structural types, the numerical type variable can be initialized by calling its constructor with the new statement,
for example: int j=new int().
Please note that using the new statement does not turn the int variable into a reference variable, j is still a value type variable, and
here new just calls its constructor. All numeric types have a default parameterless constructor, whose function is to assign an initial value to the numeric type with a default value.
For custom structure types, since there is a default parameterless constructor, no parameterless constructors can be defined, but parameterized constructors can be defined

2. Classification of reference types

  • Class: Some classes are predefined in C# language: object class (object class), array class, string class, custom class, etc.
  • No matter how the interface
    C# language reference type variable is defined, it is always a reference type variable and will not become a value type variable.
    C# language reference type objects are generally created with operator new, and reference type variables are used to refer to the object.

(1) Object class (object class)
All types (including numeric types) in C# are directly or indirectly based on the object class.
The object class (object class) is the base class of all other classes. For any class definition, if no base class is specified, object is the base class by default.
The C# language stipulates that the reference variable of the base class can refer to the object of the derived class (note that the reference variable of the derived class cannot refer to the object of the base class), so
any type of value can be assigned to an object variable

The object keyword is defined in the namespace System and is an alias for the class System.Object

(2) Array
The array in the C# language is a System.Array class object, which is basically the same as the usage of the array in java, so let's not talk about it.
(3) string: Similar to the functions in the java api, you can compare and learn. Now you can get a general understanding, and then check it when you use it. C# also defines
a basic class string, which is specially used for string operations.
This class is also defined in the namespace System, which is an alias of the class System.String
Note that the comparison of two strings compares the value: string a, b; a==b, while in java, the comparison is hashcode

5. Boxing and unboxing

Boxing and unboxing are the core concepts proposed by the C# language type system. Boxing is the conversion of a value type to an object (object) type, and unboxing is the conversion of an
object (object) type to a value type. With the concept of boxing and unboxing, we can finally regard any type of variable as an object type

It can be understood as unboxing and boxing operations in java, and automatic unboxing in java. This requires manual operation
. The more extensive in c# needs to be understood slowly in use.

6. Operators

It is almost the same as that in java. If you encounter any inconsistency, just check it directly.
(1) typeof operator: the operator is used to obtain the type name of the specified type defined in the system namespace
For example:
Console.WriteLine(typeof(System.Int32));
the output is as follows:
System.Int32
(2) Overflow check operator When checked and unchecked
perform integer arithmetic operations (such as +, -, *, /, etc.) or explicitly convert from one integer type to another, the result of the operation may exceed the value range of the type to which the result belongs. situation,
this situation is called overflow. Integer arithmetic expressions can use checked or unchecked overflow checking operators to determine whether to check expression overflow at compile and run time.
If the expression does not use the overflow check operator or uses the checked operator, the constant expression overflows, and an error will be generated at compile time. If the expression contains variables, and the expression overflows when the program is running, an exception message will be generated. However, for expression statements using unchecked operators, even if the expression overflows,
there will be no error prompts during compilation and runtime. But this often has some unpredictable results, so be careful when using unchecked operators.
The following examples illustrate the usage of checked and unchecked operators:

using System;
class Class1{
    
    
	static void Main(string[] args){
    
    
		const int x=int.MaxValue;
		unchecked//不检查溢出
		{
    
    
			int z=x*2;//编译时不产生编译错误,z=-2
			Console.WriteLine("z={0}",z);//显示-2
		}
		checked//检查溢出
		{
    
    
			int z1=(x*2);//编译时会产生编译错误
			Console.WriteLine("z={0}",z1);
		}
	}
}


(3) The difference between the new operator and java is that variables of value types (basic data types) can be created, and only objects can be created in java.
The new operator can create value type variables, reference type objects, and automatically call the constructor.
For example:
int x=new int();//Use new to create an integer variable x, and call the default constructor
Person C1=new Person ();//Use new to create a Person class object. Person variable C1 object reference
int[] arr=new int[2];//Array is also a class, create an array object, arr is a reference to an array object It should be noted that the
int x=new int() statement will be called automatically The constructor of the int structure without parameters assigns an initial value of 0 to x, and x is still a value type variable and
will not become a reference type variable

Seven, control statement

The control statement is almost the same as java. There are only differences here. There may be omissions. Please correct me. It needs to be experienced in use.
This is just a quick learning process from java to c#.
(1) foreach (type variable name in expression) loop statement
The expression must be an array or other collection type, and each cycle takes out data one by one from the array or other collection, and
assigns it to a variable of the specified type, which can be used in The variable is used and processed in the loop statement, but it is not allowed to modify the variable.
The specified type of the variable must be consistent with the data type in the array or other collection represented by the expression.
example:

using System;class Test()
{
    
    
	public static void Main(){
    
    
		int[] list={
    
    10,20,30,40};//数组
		foreach(int m in list)
			Console.WriteLine("{0}",m);
	}
}

For a one-dimensional array, the loop order of the foreach statement is from the element whose subscript is 0 to the last element of the array.
For multidimensional arrays, element subscripts are incremented starting from the rightmost dimension. Similarly break and continue can appear in the foreach statement, the function remains unchanged
(2) The exception handling statement is the same as java, try, catch, finally
insert image description here

Eight, class inheritance

(1) It is almost the same as the inheritance of classes in java, both of which are single inheritance, and constructors cannot be inherited. The
syntax format is different:
parent class: Person
subclass: Employee
subclass is defined as follows:

class Employee:Person{
    
    

}

(2) The base keyword
is used in the same way as the super keyword in java
(3) Class member types
Local variables: Variables defined in for, switch, etc. statements and class methods are only valid within the specified range.
Fields: Variables or constants in a class, including static fields, instance fields, constants, and read-only fields.
Method members: including static methods and instance methods.
Attribute: read and write fields according to the get method and set method specified by the attribute. Properties are essentially methods.
Event: Represents the event itself, and at the same time contacts the event and the event processing function.
Index pointer: Allows access to data members in the class like using an array.
Operator overloading: Use the method of overloading operators to define the unique operations in the class.
constructor and destructor.
(4)
Comparison of class modifiers of modifier c# and java

C# java
private Only accessible by this class Only accessible by this class
protected this class, derived class This class, subclass, same package
public external program this program
internal this program none
protected internal Comply with protected or internal none
default none This class, same package

(5) Fields and attributes
Fields: variables or constants
Attributes: methods with get and set (different from java, member variables with set and get methods in java are called attributes, and my understanding here may be wrong) (
6 )
Static field: a field declared with static, which is the same as a static variable in java
Instance field: an ordinary variable, which is the same as a member variable in java
Constant: a constant declared with const modification, which is the same as the static final modification in java
Read-only field: Use readonly to modify the declared field. It can only be assigned in the field declaration or in the constructor. There is no corresponding definition in java.
(7) Attributes in C# Attributes
are not fields, but must be associated with one or some fields in the class. Attributes define the methods for obtaining and modifying associated fields.
Attributes in C# more fully reflect the encapsulation of objects: the data content of the class is not directly manipulated, but accessed through the accessor, and the value of the attribute is read and written with the help of get and set
methods. The grammatical form of accessing attribute values ​​is basically the same as accessing a variable, making accessing attributes as convenient as accessing variables, which conforms to the habit.
In the section on the basic concepts of classes, define a class Person that describes personal situations, where the fields name and age are private fields, record name and age, and modify these two private
fields externally through the public methods SetName and SetAge. Now use attributes to describe name and age. Examples are as follows:

using System;
public class Person
{
    
      private string P_name="张三";//P_name是私有字段
	private int P_age=12;//P_age是私有字段
	public void Display()//类的方法声明,显示姓名和年龄
	{
    
      Console.WriteLine("姓名:{0},年龄:{1}",P_name,P_age);
	}
	public string Name//定义属性Name
	{
    
      get
		{
    
      return  P_name;}
		set
		{
    
      P_name=value;}
	}
	public int Age//定义属性Age
	{
    
      get
		{
    
      return  P_age;}
		set
		{
    
      P_age=value;}
	}
}
public class Test
{
    
      public static void Main()
	{
    
      Person OnePerson= new Person();
		OnePerson.Name="田七";//value="田七",通过set方法修改变量P_Name
		string s=OnePerson.Name;//通过get方法得到变量P_Name值
		OnePerson.Age=20;//通过定义属性,既保证了姓名和年龄按指定方法修改
		int x=OnePerson.Age;//语法形式和修改、得到一个变量基本一致,符合习惯
		OnePerson.Display();
	}
}

In the access statement of the attribute, only the set accessor indicates that the value of the attribute can only be set and cannot be read, only the get accessor indicates that the value of the attribute is read-only and cannot be rewritten, and both set accessor and get accessor indicate that the
attribute Both reading and writing of the value are allowed.
Although the syntax of attributes and fields is relatively similar, because attributes are essentially methods, attributes cannot be used as variables, and attributes cannot be passed as reference parameters or output parameters.

Nine, the type of method parameters

c# has more parameter types, which is much more complicated than java

  • Method modifiers include new, public, protected, internal, private, static, virtual, sealed, override, abstract, and extern
  • Methods in the C# language can use the following four parameters (please note the difference with the parameter type):
    Value parameters without any modifiers.
    Reference parameters are declared with the ref modifier.
    Output parameters, declared with the out modifier.
    Array parameters, declared with the params modifier.

1. Value parameter
(1) When passing a parameter to a method with a value parameter, the program makes a copy of the value of the actual parameter and passes this copy to the method. The called method will not modify the value of the actual parameter, so use the
value parameter, the value of the actual parameter is guaranteed to be safe.
(2) If the parameter type is a reference type, such as a reference variable of a class, the object reference is also stored in the copy
, so the copy and the actual parameter refer to the same object. Through this copy, the object referenced by the actual parameter can be modified data members.
Value parameters are consistent with parameter passing in java.
2. Reference parameters
Sometimes in the method, it is necessary to modify or obtain the variable value outside the method. C language uses the actual parameter pointer to the method to achieve the purpose, and C# language uses reference parameters.
When the reference parameter is used to pass the actual parameter to the method, the program will pass the reference of the actual parameter, that is, the address of the actual parameter in memory to the method, and the method will modify or obtain the value of the variable outside the method through the reference of the actual parameter
. Reference parameters are declared with the ref modifier. Note that actual parameter variables must be initialized before use.

This is similar to passing the address in C language, and then find the corresponding memory space according to the address, and modify the value of this memory space.
3. Output parameter
In order to store the operation result of the method in an external variable, it is necessary to know the reference (address) of the external variable. The output parameter is used to pass the external variable reference (address) to the method,
so the output parameter is also a reference parameter, and the difference with the reference parameter is that the variable does not need to be initialized before calling the method. After the method returns, the passed variables are considered initialized.

This is also similar to the implementation of multiple return values ​​in the C language. The difference is the initialization problem. Of course, Java can also implement the modification of references, but it cannot be done for basic data types. It can only be
implemented with the encapsulation class of basic data types. .

The use of value parameters, reference parameters and output parameters is shown in the following example

using System;
class g{
    
    public int a=0;}//类定义
class Class1
{
    
      public static void F1(ref char i)//引用参数
	{
    
      i='b';}
	public static void F2(char i)//值参数,参数类型为值类型
	{
    
      i='d';}
	public static void F3(out char i)//输出参数
	{
    
      i='e';}
	public static void F4(string s)//值参数,参数类型为字符串
	{
    
      s="xyz";}
	public static void F5(g gg)//值参数,参数类型为引用类型
	{
    
      gg.a=20;}
	public static void F6(ref string s)//引用参数,参数类型为字符串
	{
    
      s="xyz";}
	static void Main(string[] args)
	{
    
      char a='c';
		string s1="abc";
		F2(a);//值参数,不能修改外部的a
		Console.WriteLine(a);//因a未被修改,显示c
		F1(ref a);//引用参数,函数修改外部的a的值
		Console.WriteLine(a);//a被修改为b,显示b
		Char j;
		F3(out j);//输出参数,结果输出到外部变量j
		Console.WriteLine(j);//显示e
		F4(s1);//值参数,参数类型是字符串,s1为字符串引用变量
		Console.WriteLine(s1);//显示:abc,字符串s1不被修改
		g g1=new g();
		F5(g1);//值参数,但实参是一个类引用类型变量
		Console.WriteLine(g1.a.ToString());//显示:20,修改对象数据
		F6(ref s1);//引用参数,参数类型是字符串,s1为字符串引用变量
		Console.WriteLine(s1);//显示:xyz,字符串s1被修改
	}
}

4. Array parameters
Array parameters use params to describe,
(1) If the formal parameter list contains an array parameter, it must be the last parameter in the parameter list, and the array parameter is only allowed to be a one-dimensional array.
For example, both string[] and string[][] types can be used as array parameters.
(2) Array parameters cannot have ref and out modifiers. See example below:

using System;
class Class1
{
    
      static void F(params int[] args)//数组参数,有params说明
	{
    
      Console.Write("Array contains {0} elements:",args.Length);
		foreach (int i in args)
			Console.Write(" {0}",i);
		Console.WriteLine();
	}
	static void Main(string[] args)
	{
    
      int[] a = {
    
    1,2,3};
		F(a);//实参为数组类引用变量a
		F(10, 20, 30, 40);//等价于F(new int[] {60,70,80,90});
		F(new int[] {
    
    60,70,80,90});//实参为数组类引用
		F();//等价于F(new int[] {});
		F(new int[] {
    
    });//实参为数组类引用,数组无元素
	}
}

program output

Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 4 elements: 60,70,80,90
Array contains 0 elements:
Array contains 0 elements:

Similar to the usage of variable parameters in java, it is the same when passing parameters, but different when defining, but it must be the last parameter in the parameters

5. The usage of static methods and member methods in C# and
java is the same

10. Operator overloading

Operators cannot be overloaded in java

Operator overloading is to give new functions to the existing operators in the C# language, but it does not conflict with the original meaning of the operator. When using it, you only need to
judge which operation it performs according to the position where the operator appears. Operator overloading actually defines an operator function. The format of the operator function declaration is as follows:

static public 函数返回类型 operator 重新定义的操作符(形参表)

Some operators in the C# language can be overloaded, for example: + - ! ~ ++ – true false * / % & | ^ << >> == != > < >= <= and so on.
But there are also some operators that are not allowed to be overloaded, for example: =, &&, ||, ?:, new, typeof, sizeof, is, etc.

Eleven, this keyword

The this keyword is consistent with the usage of this in java.
Note: super in java uses base in C#

Twelve, class polymorphism

C# supports two types of polymorphism.
The first is compile-time polymorphism. An object of a class calls several methods with the same name. When the system compiles, it decides to call according to the actual parameter type and the number of actual parameters of the calling method. The method with the same name,
what kind of operation is achieved. Compile-time polymorphism is achieved through method overloading.
The second is run-time polymorphism. When the system is running, different objects call a method with the same name and exactly the same type and number of parameters to complete different operations.
Polymorphism at runtime in C# is implemented through virtual methods. Adding the virtual modifier before the method declaration of the class is called a virtual method, and vice versa is a non-virtual method.

The first polymorphism is the same as java, but the usage is different. When the method is executed, the method of the base class is executed. The
second polymorphism is different from java, and the subclass inheritance is also different, but it has the same meaning as java inheritance.
The base class return value is modified with the virtual keyword, and when the derived class inherits, an override keyword is added before the return value to modify.

13. Abstract classes and abstract methods

Compared with java, it is basically the same, but there is a little difference in writing. Java can use annotations. I don’t know if C# can

14. Sealing type and sealing method

Classes or methods modified with sealed in C# are called sealed classes and sealed methods, which are the same as classes and methods modified with final in java and cannot be inherited

15. Interface

The meaning and usage of the interface in java are almost the same. The difference is that C# can have methods, properties, index indicators and events in the interface, which cannot be constants, fields, operators, constructors or destructors, and cannot contain any static member.
insert image description here

16. Representatives

What I want to introduce here is a reference type of C# - delegate (delegate), which is also translated as a delegate, which can be used as a proxy in java, or can be understood as a pointer transfer in c. Check the syntax yourself, it is relatively simple
.

17. Events

Event is a built-in grammar of C# language, which can define and handle events, and provides a good foundation for using component programming

Eighteen, event-driven

The Windows operating system regards the user's actions as messages, which are called events in C#, such as clicking a button with the left mouse button to send a mouse click button event.
The Windows operating system is responsible for unified management of all events, and sends events to various running programs. Each program responds to events with event functions, which is also called event-driven.
It is basically similar to the processing of view events such as buttons in android.

19. Index indicator

In C# language, arrays are also classes. For example, we declare an array of integers: int[] arr=new int[5], which actually generates an array-like object. arr is the reference (address) of this object. To access
this The method of array elements is: arr[subscript], in the array class, how to use index to access elements?
Can I define my own class and use index to access the data members in the class? The index indicator (indexer) provides us with a convenient way to access the data members of the class through the index.

It can be understood that it is an array defined by yourself, and the elements in it can be accessed through the following table

20. Namespace namespce

The usage is similar to the package package in java.
The namespace is also used to uniquely identify the class, which is the same as the package. The
namespace can define sub-namespaces, and the package can define sub-packages.
Namespaces are different from those in java. Except for the different writing styles, namespaces are only logical classifications.

21. Other differences

1. C# can use pointers, and the unsafe keyword can be used to modify methods or lines of code, indicating that this is unsafe code, which requires the use of c pointers. 2. C
# methods, variables, and parameters are capitalized, while java is lowercase.

I found that C# is more object-oriented, but there are still shadows of C and C++.

Summarize

Of course, the above is just a comparative study of the basic syntax of C# and java, which can allow java programmers to quickly learn the C# language and understand C# programs. These are enough, just a matter of familiarity. The learning of the API of the C# SDK should also learn the corresponding learning of java, so that the learning will be very fast, and it can also deepen the understanding of java.

Guess you like

Origin blog.csdn.net/weixin_44816664/article/details/130575564