1. Basic structure of C# program The
first step is to create a new C# project
VS will automatically generate some basic code
using System;//引用命名空间
namespace boke_01//定义命名空间
{
class Program//定义类
{
static void Main(string[] args)//定义方法,这里是创建项目时自动创建好的主程序方法
{
//程序的入口点
}
}
}
First understand the Main function. It is the entry point of the program. Under normal circumstances, a project can only have one Main function, otherwise it will fail to compile, and the Main function must be static (with static keyword)
C# input and output method
static void Main(string[] args)
{
//输出
Console.WriteLine("hello C# !");
//输入
//Console.ReadLine会返回string类型,一般会声明一个string类型变量来接收
string input = Console.ReadLine();
}
2. C# commonly used variable types
(1) Value types (Value types)
Value type variables can be directly assigned to a value. They are derived from the class System.ValueType.
bool boke;//bool值,值为true或者false,默认为false
char s = 'a';//字符类型
int num = 2;//32位,整数类型
long num1 = 2;//64位,整数类型
float number = 2.3f;//单精度浮点型,f 表示float类型
double number1 = 4.6d;//双精度浮点型,d 表示double类型
byte byte_b = 2;//byte类型,0-255,此语句中其实是将整数 1 隐式转换为byte类型
(2) Reference types Reference types
do not contain actual data stored in variables, they refer to a memory location. When using multiple variables, the reference type can point to a memory location. If the data in the memory location is changed by a variable, other variables will automatically reflect this change in value. The built-in reference types are: object, dynamic and string.
[1] Object type·
In C#, Object type is the root of all types, and Object data type can point to data of any data type
object obj = "cxk";
object obj1 = 123;
But note: when a value type is converted to an object type, it is called boxing; on the other hand, when an object type is converted to a value type, it is called unboxing.
Although the Object type is more convenient to use, the unpacking and unpacking operations consume performance and depend on the situation.
[2] Dynamic (Dynamic) type
can store any type of value in a variable of dynamic data type. The type checking of these variables occurs at runtime.
dynamic dy = "dsfsd";//动态类型
The most commonly used dynamic type is to always store json data.
[3] String type
string str = "lay";//字符串类型
//表示路径的时候,前面加@,将‘/’当成普通字符处理,否则可能会识别为转义符
string path = @"C:\Users\Public\Desktop\腾讯QQ.lnk";
[4] Pointer type
When a code block is marked with the unsafe modifier, C# allows pointer variables to be used in the function.
But this is unsafe code.
static unsafe void Main(string[] args)
{
int p1 = 20;
int* p = &p1;//将地址赋给指针
}
static void Main(string[] args)
{
unsafe
{
int p1 = 20;
int* p = &p1;//将地址赋给指针
}
}
It should be noted that C# is a strictly case-sensitive language.