Visual Studio for Mac
学习一门语言总要有一个可以编写代码的平台吧,我自己用的是Visual Studio的Mac版本。Visual Studio的上手比较快捷,只需要在官网上面下载,然后按部就班安装好就能够使用了。然后选择创建一个控制台项目,如下所示:
控制台项目生成以后,会自动为你写好Hello World的代码,然后点击左上角的运行按钮即可正常执行C#代码:
最终的结果如下所示:
基本要点
- namespace是一系列类的集合,如mainApplication中可以定义多个类,如上述中HelloWorld就是mainApplication的一个类。
- using则用于包含系统中的命名空间,有点类似于C语言的include。
- class可以定义多个方法,而方法是类行为的体现。
- Main函数是C#程序的入口点,Main函数表明程序需要执行的语句。
- Console.ReadKey()的作用是等待用户任意按下一个按钮,防止程序执行结束后终端迅速消失。
- Main函数必须要声明为静态函数,因为如果Main函数不是静态的话,那么他就需要先创建一个对象,然后由对象来调用Main函数,这与Main函数是程序的入口是相互矛盾的。
- Main函数在编译时后默认设置为private修饰符。
- C#是大小写敏感的程序设计语言。
- C#的语句和表达式必须以;结束。
- C#程序由Main函数开始执行。
- C#的类名可以和文件名不同。
String和string
string是C#中的类,而String是Framework的类,string是C#的关键字,而String不是,因此String可以作为类、成员方法、字段、变量等的名称,如执行下述代码:
using System;
namespace MainFunction
{
class MainClass
{
public static void Main(string[] args)
{
String();
}
public static void String()
{
Console.WriteLine("I am String");
}
}
}
执行的结果如下:
- string是String的别名,因此如果使用string的话,编译器会把他编译为String,因此使用String会在一定程度上减少编译器的工作量。
- String只有引用using System的时候并且当前命名空间中没有String的同名时,才能够起到作用。
- 使用string是比较规范的写法。
- String是不可改变的,即对象一旦生成就不能够改变,即如果给String赋予新的值,那么他只是指向了新创建的对象而并没有修改原来对象的值。
我们可以试试去掉using System
可以发现在去掉using System以后,String有了红色的下划线。
C#传值和传引用
传值的情况
- Struct
- Numeric (Integral/Floating/decimal)
- bool
传引用的情况
- class
- Delegate
- Interface
值传引用的方法:数组、ref关键字
C# 数据类型
Value Type
Value Type能够被直接赋值和修改,具体的类型如下表所示:
Type | Represents | Default Value |
---|---|---|
bool | Boolean Value | False |
byte | 8-bits unsigned integer | 0 |
char | 16-bits Unicode character | ‘\0’ |
decimal | 128-bit precise decimal values with 28-29 significant digits | 0.0M |
double | 64-bit double-precision floating point type | 0.0D |
float | 32-bit single-precision floating point type | 0.0F |
int | 32-bit signed integer type | 0 |
long | 64-bit signed integer type | 0L |
sbyte | 8-bit signed integer type | 0 |
short | 16-bit signed integer type | 0 |
uint | 32-bit unsigned integer type | 0 |
ulong | 64-bit unsigned integer type | 0 |
ushort | 16-bit unsigned integer type | 0 |
Reference Type
- Object
- Dynamic
- String
Pointer Type
指针需要在不安全的环境中使用,即需要开启unsafe模式。
Reference
https://www.cnblogs.com/rosesmall/p/8351808.html
https://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm