C#学习(一)——基础语法

本文介绍了C#编程中的控制台输入输出操作、变量和数据类型(包括基本类型和字符串处理)、决策结构(if,switch,三元运算),以及循环、方法声明、访问修饰符、参数传递(值传参、引用传参)等内容。
摘要由CSDN通过智能技术生成

一、控制台IO

  1. Write()与WriteLine()区别
    Write()为直接输出;
    WriteLine()为输出后光标换行

  2. Read(),ReadKey()与ReadLine()
    Read():读取用户键盘操作,每次读取用户的第一次键盘操作,输出为键入的ASCII码
    ReadLine():无长度限制,读取用户输入的全部数据直至按下回车
    ReadKey():可以读取一些特殊字符,例如读取回车

ConsoleKeyInfo a = Console.Readkey();
Console.writeLine(a.key);
  1. Clear()
    清除命令行内容

二、变量(Variable)与数据类型(Data Type)

  1. 基本数据类型
    常见数据类型

  2. 字符串常用操作

字符串拼接,使用“+”

onsole.WriteLine("Hello,“+” ALEX!");

字符串格式化处理

string name = "John";
int age = 18;
Console.WriteLine("My name is {0}, I am {1} years old.", name, age);
string message = "My name is {0}, I am {1} years old.";
string output = string.Format(message, name, age);
Console.WriteLine(output);

字符串内嵌

string message2 = $"My name is {name}, I am {age} years old.";
Console.WriteLine(message2);

愿意字符串

string message3 = @"My name is {name},
 I am {age} years old.";
Console.WriteLine(message3);

三、代码决策

if(){
}else if{
}else{
}
switch(){
case:  ; break;
case:  ; break;
default:   ; break;
}

三元运算

condition ? consequent1 : consequent2

四、循环

for loop
while loop
do while loop

五、方法

方法签名

<访问修饰符> <声明修饰符> <返回类型> <方法名称> (参数列表) {
method body
}

//访问修饰符:
public, private, protected, 
private protected, internal, protected internal//内部方法,同一个程序集中的所有类都可以访问
//声明修饰符
static//表示静态类型
abstract//表示抽象类型
virtual//允许派生类重写的虚函数
override//允许方法继承后重写
new//可以隐藏基类成员
sealed//表示不能被继承
partial//允许在同一个程序集分散定义
extern//用于声明外部实现的extern

方法表达式

public static int FindMax(int num1, int num2)
{
    int result;
    if (num1 > num2)
    {
        result = num1;
    }
    else
    {
        result = num2;
    }
    return result;
}
public static int Findmax(int num1, int num2) =>
    num1 > num2 ? num1 : num2;

六、传参

值传参
参数默认传递方式
为每个值参数创建一个新的存储位置
当形参的值发生改变时,不会影响实参的值,实参数据安全
函数传参

static void swap(ref int x, ref int y)//reference,参数的引用
{
	int temp;
	temp = x;
	x = y;
	y = temp;
}

static void Main(string[] args)
{
	int a = 100;
	int b - 500;
	swap(ref a, ref b);
}

输出传参

static void swap(ref int x, ref int y)
{
	int temp;
	temp = x;
	x = y;
	y = temp;
}

static void getValue(out int x)
{
	x = 5;
}

static void Main(string[] args)
{
	int a = 100;
	int b - 500;
	swap(ref a, ref b);
	
	getValue(out a);//直接将方法内部的数据传出去
}
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值