C#基础语法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37813928/article/details/80568601

1.标识符(Identifiers)

变量命名规则:
必须以字母或下划线开头;
只能由字母、数字、下划线组成;
不能与C#关键字同名。

特殊情况:可以使用“@”符号将关键字用作标识符
Ex:if 是关键字 ; @if 作为标识符if
可能包含Unicode转义序列,如b\u0061ck  the identifier back
字符串:
"file \"C:\\sample.txt\""  file "C:\sample.txt"
"file \x0022C:\u005csample.txt\x0022"
“\”被当作转义符
特殊情况:字符串前面被冠以“@” the \ is not interpreted as a escape character \不再被看做转义符any " must be doubled 引号必须双倍the string may span several lines 字符串可能跨越多行Ex:@"file" file@"""C:\sample.txt""" "C:\sample.txt"

2.数据类型

重点是相较java特有的数据类型。

sbyte  范围是-128~127 byte范围是0~255
ushort 0~65535
uint   0~2^32-1
ulong  0~2^64-1
decimal  128bit

Structs

Delegates

值类型和引用类型

value type               reference type
存放在栈上stack           存放在堆上heap
初始化 0,false,‘\0’     null

3.

static void Main(string[] args)中的string[] args用来接收命令行传入的参数,它是可选的,不是必须的。

4.结构体struct

①结构体不能在声明时初始化

struct Point{
    int x=0; //编译错误
}

②结构体既不能继承,也不能被继承,但可以实现接口

5.可见性标识符

public    命名空间内可见

private   只有在声明的类或结构体中可见

如未声明,结构体和类的成员默认为private;接口和枚举成员默认为public

6.

①常量数据必须在声明时初始化,只读类型readonly必须在声明或构造函数中初始化

②static静态类型成员属于类而不属于某个对象

不能将常量声明为静态类型

7.ref 和 out

Ref和Out都是引用传递,Ref的重点是把值传给调用方法,Out则是得到调用方法的值,类似于有返回类型的方法返回的值;

在使用两者时一定要注意一下两点,否则编译出现错误

a) ref 变量使用前要先声明同时要赋值 a=20;

b)方法调用参数要加上相应的关键字 ref or out;

static void main()
{

int a = 20;
int b = 30;
int c;

//把"a","b"引用传进去,虽然此方法没有返回值,但是两者值已经调换
SwapMethod(ref a, ref b);

Console.WriteLine(" After Swap a is {0},b is {1} ",a,b);

//"out"可以理解成传进去的引用"c"经过一系列的处理,结果就是值也发生了变化
OutTest(out c);

Console.WriteLine("The out value is {0}.",c);

}

static void SwapMethod(ref int a,ref int b)
{
int tem;
tem = a;
a = b;
b = tem;
}

static void OutTest(out int a)
{
a = 10 * 10;
}

输出结果:

After Swap A is 30,B is 20

The out value is 100.

8.

①一个类不声明构造函数,编译器就会自动生成一个默认的无参构造。

②如果类中声明了构造函数,就不会自动生成无参构造函数了。

class C{
    int x;
    public C(int y)
    { x=y;}
}

C c1=new C(); //错误
C c2=new C(3); //正确

③对于所有的struct,编译器都会自动生成一个默认的无参构造(即使已经人为定义了其他构造),所以不能再人为定义无参构造。

9.static 构造

class Rectangle {
...
static Rectangle() {
Console.WriteLine("Rectangle initialized");
}
}
struct Point {
...
static Point() {
Console.WriteLine("Point initialized");
}
}

注意事项:

①必须无参,没有public 或 private修饰符,并且最多只能有一个

②在相应类型使用之前调用一次,用来初始化静态字段

10.Destructors析构函数

①析构函数在垃圾收集器回收对象之前调用
②最后自动调用基类的析构函数

③结构struct不能有析构函数

11.嵌套类型

内部类可以访问外部类的所有成员(即使是私有成员)

外部类只能访问内部类的public成员

内部类是public时才能被其他类访问

猜你喜欢

转载自blog.csdn.net/qq_37813928/article/details/80568601