首页 > 编程语言 >01 C#的基本语法概念A

01 C#的基本语法概念A

时间:2024-07-21 18:55:29浏览次数:10  
标签:01 Console string WriteLine C# 语法 int str 数组

(一) C# 程序结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace netBasic_learning
{
//类的定义
class Rectangle
{
//(1)属性
double length;
double width;
//(2)方法
public void Acceptdetails()
{
this.length = 4.5;
this.width = 2;
}

    public double getArea()
    {
        return this.length * this.width;
    }

    public void Display()
    {
        Console.WriteLine("Length: {0}", length);
        Console.WriteLine("Width: {0}", width);
        Console.WriteLine("Area: {0}", getArea());
    }

    //Main函数是程序的主入口
    public  static void Main(string[] args)
    {
        Rectangle rectangle = new Rectangle();
        rectangle.Acceptdetails();
        rectangle.Display();
        //阻塞窗口
        Console.ReadLine();
    }

}

}
1.using的使用:
(1)含义:使用命名空间,类似于Java的Import
(2)注意:using 关键字用于在程序中包含命名空间。一个程序可以包含多个 using 语句。

2.namespace的使用:
(1)namespace声明本类的命名空间为netBasic_learning,其他地方可以通过using netBasic_learning来使用此处的类和方法
(2)一个namespace内可以包含多个类

3.Main函数的阻塞:

(1)Console.ReadLine() : 最后一行 Console.ReadLine(); 是针对 VS.NET 用户的。这使得程序会等待一个回车的动作,防止程序从 Visual Studio .NET 启动时屏幕会快速运行并关闭。即防止黑窗口一闪而过,阻塞一下。同时ReadLine()方法还可以用于读取程序输入。 (2)Console.ReadKey() : 其作用同上。

4.总结:
1.C#语法基本与Java差不多,都是面向对象的语言。只不过C#主要面向桌面应用开发,Java主要面向Web应用开发
2.C#与 Java 不同的是,文件名可以不同于类的名称。

(二) C# 数据类型与变量

  1. 基本数据类型

    namespace netBasic_learning
    {
    class Basic_dataType
    {
    public static void Main(String[] args)
    {
    //1.基本数据类型:分配存储空间,存放数据
    int Int_number = 1;
    double Double_number = 3.14;
    bool Bool_number = true;
    Console.WriteLine("Int: {0},Double: {1},Bool: {2}", Int_number,Double_number,Bool_number);//自动换行
    }
    }
    }
  2. 引用类型
    引用类型不包含存储在变量中的实际数据,但它们包含对变量的引用。换句话说,它们指的是一个内存位置。使用多个变量时,引用类型可以指向一个内存位置。如果内存位置的数据是由一个变量改变的,其他变量会自动反映这种值的变化。内置的 引用类型有:object、string和我们自定义的类Class
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

namespace netBasic_learning
{
class Basic_dataType
{
public static void Main(String[] args)
{
//引用数据类型:存放数据的引用地址,即别名(Object、String、class)
String str = "Hello World!";
String str_origin = "Hello\nWorld!";//转义字符
String str_change = @"Hello\nWorld!";//原样输出 @ = "\"
Console.WriteLine("String str: {0}", str);
Console.WriteLine("String str_origin: {0}", str_origin);
Console.WriteLine("String str_change: {0}", str_change);

    }
}

}
3. 数据类型转换
一.数据类型转换
(1)隐式类型转换:安全转换,不会造成数据丢失。比如从派生类转换为基类,小范围类型->大范围类型int->long,float->double,在一些计算中会自动转换发生
(2)显式类型转换:不安全转换,可能会造成数据丢失。比如double->int
(3)内置的类型转换方法:int.Parse()、ToString()等
namespace netBasic_learning
{
class Basic_dataType
{
public static void Main(String[] args)
{
//数据类型转换
// (1)隐式类型转换:安全转换,不会造成数据丢失。比如从派生类转换为基类,小范围类型->大范围类型int->long,float->double,在一些计算中会自动转换发生
// (2)显式类型转换:不安全转换,可能会造成数据丢失。比如double->int
double a = 3.1415;
int b = (int)a;//向下取整,丢失精度
Console.WriteLine("Double->Int: {0}", b);
// (3)内置的类型转换方法
string num = "66";
Console.WriteLine("Int -> String: {0}",a.ToString());
Console.WriteLine("String -> Int: {0}", int.Parse(num));
//4.常量:const ,运行期间不能被修改
Console.ReadLine();
}
}
}
4. 字符串string类型
一.字符串:使用 string 关键字来声明一个字符串变量。string 关键字是 System.String 类的别名。
1.字符串构建:
- "":string str = "hello world!";
- +:string str = a + b;(字符串拼接)

    2.字符串常用方法:
         - public static int Compare( string strA, string strB ):比较两个指定的 string 对象(按ASCII),并返回一个表示它们在排列顺序中相对位置的整数。
         - public static string Concat( string str0, string str1 ):连接两个 string 对象。相当于+
         - public bool Contains( string value ):判断字符串是否包含字串value
         - public bool EndsWith( string value ):判断 string 对象是否以value结尾。
         - public bool StartsWith( string value ):判断字符串实例的开头是否匹配指定的字符串。
         - public bool Equals( string value ):判断当前的 string 对象是否与指定的 string 对象具有相同的值。
         - public static string Format( string format, Object arg0 ):把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。
         - public int IndexOf( string value/char ch ):返回指定字符串在该实例中第一次出现的索引,索引从 0 开始。
         - public int LastIndexOf( string value/char value ):返回指定字符串在该实例中最后一次出现的索引,索引从 0 开始。
         - public string Insert( int startIndex, string value ):返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。
         - public static string Join( string separator, string[] value ):连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。
         - public string Remove( int startIndex ):移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。
         - public string Replace( string oldValue, string newValue ):把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。
         - public string[] Split( params char[] separator ):返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。
         - public char[] ToCharArray():返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。
         - public string ToLower()/ToUpper()/Trim()

namespace netBasic_learning
{
class Basic_string
{

    public static void mains(string[] args)
    {
        //  (1)字符串构建:
        string a_str = "Hello,";
        string b_str = "World!,Write the code,change the world.";
        string strs = a_str + b_str;
        Console.WriteLine(strs);
        /**
         *(2)字符串方法、操作(重点):
         */
        //2.字符串比较
        string c_str = "Hello,";
        if(a_str == c_str)//==在引用数据里,比较的是地址。因此两个数据相同的变量可能是“不相等的”。
        {
            //但是此处是相等的,原因是string是常量,地址也相同。
            Console.WriteLine("== 比较符号:a_str 与 c_str 相同");
        }
        if (a_str.Equals(c_str))//Equals比较的是数值大小是否相同,推荐!
        {
            Console.WriteLine("Equals 比较函数:a_str 与 c_str 相同");
        }
        int res = String.Compare(a_str, b_str);//a_str<b_str是比较<0;a_str=b_str是=0;a_str>b_str是>0
        Console.WriteLine("排序结果: {0}",res);
        //2.字符串包含
        if (strs.Contains("World"))
        {
            Console.WriteLine("{0}包含{1}", strs,"World");
        }
        //3.字串获取
        string child_str = strs.Substring(15);
        Console.WriteLine(child_str);
        //4.字符串合并
        string[] str_arrays = { "hello", "world", "i'm", "OK" };
        string join_str = String.Join("-", str_arrays);
        Console.WriteLine(join_str);
        //5.字符串分割
        string[] str_list = join_str.Split('-');
        foreach(string factor in str_list)
        {
            Console.WriteLine(factor);
        }
        //6.字符串格式化

        Console.ReadKey();

    }
}

}
(三)C#计算与条件、循环

  1. 计算语句
    1.算术运算符:+、-、、/、%、++、--
    2.关系运算符:、!=、>、<、>=、<=
    3.逻辑运算符:&&、||、!
    4.位运算:&(与,全1才1)、|(或,一1即1)、^(异或,相异即1)、<<(左移,右补0)、>>(右移,左补0)
    5.赋值运算符:+=、-=、/=、%=、&=、<<=
    6.其他运算符:
    (1)?: 三元表达式 a
    1?xxx:yyy
    (2)& 取地址
    (3)
    指针
    (4)sizeof、typeof、is
    namespace netBasic_learning
    {
    class Basic_calculate
    {
    public static void Main(string[] args)
    {
    //算术运算
    double y = 5 / 2; //如果/法都为整数,则运算结果也为整数(向下取整)
    double y_2 = 5.0/2;//如果/法有一个为浮点数,则运算结果自动向大类型转换
    Console.WriteLine(y);
    Console.WriteLine(y_2);
    //总结:运算与Java差不多-。-
    Console.ReadLine();
    }
    }
    }

  2. 条件选择
    一.条件判断:
    (1)if...else if...else
    (2)switch(Expression){
    case condition1:
    break;
    case condition2:
    break;
    default:
    }
    namespace netBasic_learning
    {
    class Basic_calculate
    {
    public static void Main(string[] args)
    {
    double y = 5 / 2; //如果/法都为整数,则运算结果也为整数(向下取整)
    //条件判断:
    if (y>0)
    {
    Console.WriteLine("y > 0");
    }else if (y == 0)
    {
    Console.WriteLine("y = 0");
    }
    else
    {
    Console.WriteLine("y < 0");
    }
    Console.ReadLine();
    }
    }
    }

  3. 循环分支
    一.循环语句
    (1) for:for(初始化,判断,循环操作){循环语句}、foreach()
    (2) while:只要给定的条件为真,会重复执行一个目标语句。先判断再执行
    (3)do..while:在循环的尾部检查它的条件。会确保至少执行一次循环。
    (4)循环控制语句:break跳出循环,continue直接继续循环
    namespace netBasic_learning
    {
    class Basic_calculate
    {
    public static void Main(string[] args)
    {
    //循环语句
    // (1)for:for(初始化,判断,循环操作){循环语句}
    // (2)while:只要给定的条件为真,会重复执行一个目标语句。先判断再执行
    // (3)do..while:在循环的尾部检查它的条件。会确保至少执行一次循环。
    // (4)循环控制语句:break跳出循环,continue直接继续循环
    for (int i = 0; i < 10; i++)
    {
    Console.WriteLine(i);
    }
    Console.ReadLine();
    }
    }
    }
    (四). C# 数组

  4. 可空类型
    1.可空类型(null):可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。
    (1)声明可空类型:
    - 基本数据:? 单问号用于对 int、double、bool 等无法直接赋值为 null 的数据类型进行 null 的赋值。比如:int? num1 = null;
    - 类与对象:直接声明

     (2)null合并运算符(??):判断如果第一个操作数的值为 null,则运算符返回第二个操作数的值,否则返回第一个操作数的值。
         - 使用:a = b ?? c
         - 本质:a = (b==null)?c:b
    

namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
//1.可空类型(null):可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。
// (1)声明可空类型:
int? num1 = null;//可空int类型取空值
int? num2 = 66;//可空int类型不取空值
double? num3 = null;
double? num4 = 3.1415;
Console.WriteLine("显示可空类型的值: {0}, {1}, {2}, {3}",num1, num2, num3, num4);
if(num1 == null)//空值判断
{
Console.WriteLine("Int数据num1为空值");
}
Rectangle rect = null;//类&对象空值声明
if(rect == null)//类&对象空值判断
{
Console.WriteLine("Rectangle类对象rect为空");
}
// (2)null合并运算符(??):判断如果第一个操作数的值为 null,则运算符返回第二个操作数的值,否则返回第一个操作数的值。
double? b = null;
double? c = 3.1415;
double? a = b ?? c;//b如果为空则返回c
Console.WriteLine("a 的值: {0}", a);

        Console.ReadKey();
    }

}

}
2. 数组
1.数组:数组是一个存储【相同类型元素】的固定大小的顺序集合
(1)声明数组:double[] arrays; 声明一个数组不会在内存中初始化数组。
(2)初始化数组:double[] balance = new double[10];数组是一个引用类型,所以您需要使用 new 关键字来创建数组的实例。
(3)数组赋值:
- 索引赋值: balance[0] = 3.14;
- 声明数组的同时给数组赋值: double[] balance = { 2340.0, 4523.69, 3421.0};
- 创建并初始化一个数组: int [] marks = new int[5] { 99, 98, 92, 97, 95};
- 省略数组的大小:int [] marks = new int[] { 99, 98, 92, 97, 95};
- 赋值一个数组变量到另一个目标数组变量中。在这种情况下,目标和源会指向相同的内存位置(引用):int[] score = marks;
(4)数据访问、遍历:[]下标访问+for、foreach循环

   (5)多维数组:int[,] a;声明二维数组,int[, ,] a;声明三维数组

   (6)交错数组:交错数组是数组的数组。交错数组是一维数组,每个元素是一个数组
        - 声明:int [][] scores;int数组的一维数组,声明一个数组不会在内存中创建数组
        - 初始化:int[][] scores = new int[5][];含有五个元素
        - 初始化赋值:int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
        - 访问:scores[i][j] 取第i个子数组的第j个元素(类似于二维数组)

namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
//1.数组:数组是一个存储【相同类型元素】的固定大小的顺序集合
// (1)声明数组:double[] arrays; 声明一个数组不会在内存中初始化数组。
// (2)初始化数组:double[] balance = new double[10];数组是一个引用类型,所以您需要使用 new 关键字来创建数组的实例。
// (3)数组赋值:
// - 索引赋值: balance[0] = 3.14;
// - 声明数组的同时给数组赋值: double[] balance = { 2340.0, 4523.69, 3421.0};
// - 创建并初始化一个数组: int [] marks = new int[5] { 99, 98, 92, 97, 95};
// - 省略数组的大小:int [] marks = new int[] { 99, 98, 92, 97, 95};
// - 赋值一个数组变量到另一个目标数组变量中。在这种情况下,目标和源会指向相同的内存位置(引用):int[] score = marks;
// (4)数据访问、遍历:[]下标访问+for、foreach循环
int[] List = new int[10];
for(int i = 0; i < List.Length; i++)
{
List[i] = i*2;
}
foreach(int j in List)
{
Console.WriteLine("Element = {0}",j);
}
// (4)多维数组:int[,] a;声明二维数组,int[, ,] a;声明三维数组
int[,] matrix = new int[3, 4];//初始化3x4的二维数组
int[,] matrix_2 = new int[3, 4]{//初始化并赋值
{0,1,2,3 }, //初始化第0行
{4,5,6,7}, //初始化第1行
{8,9,10,11} //初始化第2行
};
for(int i = 0; i < matrix_2.GetLength(0); i++)//循环遍历多维数组
{
for(int j = 0; j < matrix_2.GetLength(1); j++)
{
Console.WriteLine("矩阵({0},{1})的值为{2}", i,j, matrix_2[i,j]);
}
}
// (5)交错数组:交错数组是数组的数组。交错数组是一维数组,每个元素是一个数组
// - 声明:int [][] scores;int数组的一维数组,声明一个数组不会在内存中创建数组
// - 初始化:int[][] scores = new int[5][];含有五个元素
// - 初始化赋值:int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
// - 访问:scores[i][j] 取第i个子数组的第j个元素(类似于二维数组)
int[][] scores = new int[5][];
for (int i = 0; i < scores.Length; i++)
{
if (i <= 2) scores[i] = new int[3];
else scores[i] = new int[5];
for(int j = 0; j < scores[i].Length; j++)
{
scores[i][j] = i * j + 6;
}
}
for (int i = 0; i < scores.Length; i++)
{
for (int j = 0; j < scores[i].Length; j++)
{
Console.WriteLine("子数组{0}下标{1}的值为{2}", i, j, scores[i][j]);
}
}

        Console.ReadKey();
    }

}

}
(7)Array 类:Array 类是 C# 中所有数组的基类,提供了很多属性和方法
- Array.Clear:根据元素的类型,设置数组中某个范围的元素为零、为 false 或者为 null。
- Array.IndexOf(Array, Object):搜索指定的对象,返回整个[一维数组]中第一次出现的索引。
- Array.Reverse(Array):逆转整个一维数组中元素的顺序。
- Array.Sort(Array):使用数组的每个元素的 IComparable 实现来排序整个一维数组中的元素。
namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
// (6)Array 类:Array 类是 C# 中所有数组的基类,提供了很多属性和方法
// - Array.Clear:根据元素的类型,设置数组中某个范围的元素为零、为 false 或者为 null。
// - Array.IndexOf(Array, Object):搜索指定的对象,返回整个[一维数组]中第一次出现的索引。
// - Array.Reverse(Array):逆转整个一维数组中元素的顺序。
// - Array.Sort(Array):使用数组的每个元素的 IComparable 实现来排序整个一维数组中的元素。
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
Console.Write("原始数组: ");
foreach (int i in list)
{
Console.Write(i + " ");//不换行输出
}
Console.WriteLine();//输出换行

        // 逆转数组
        Array.Reverse(list);//改变原数组
        Console.Write("逆转数组: ");
        foreach (int i in list)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();

        // 排序数组
        Array.Sort(list);//改变原数组,默认由小到大
        Console.Write("排序数组: ");
        foreach (int i in list)
        {
            Console.Write(i + " ");
        }
        Console.ReadKey();
    }

}

}
(五) 列表与字典
1.ArrayList:动态数组列表集合,类似于Java的List

标签:01,Console,string,WriteLine,C#,语法,int,str,数组
From: https://www.cnblogs.com/chengrong/p/18314779

相关文章

  • Elasticsearch 入门实战(8)--REST API 使用二(Search API)
    本文继续上文(Elasticsearch入门实战(3)--RESTAPI使用一(CAT,Index,Document,IngestAPI))介绍ElasticsearchRESTAPI,相关的环境及软件信息如下:CentOS 7.6.1810、Elasticsearch8.13.4。1、SearchAPIs1.1、CountAPI(查询文档数量)语法:GET/<target>/_count样例:cu......
  • Codeforces Round 958 (Div. 2)
    A.SplittheMultisetForexample, {2,2,4} isamultiset.Youhaveamultiset ......
  • /etc/hosts与域名解析
    `/etc/hosts`是一个计算机文件,用于在Unix和类Unix操作系统(比如Linux、macOS等)中映射主机名和IP地址。它允许将特定的主机名映射到指定的IP地址,从而绕过DNS解析过程,实现本地对特定主机名的自定义解析。通常情况下,`/etc/hosts`文件包含了一些基本的条目示例,如:```127.0.0.1loc......
  • I2C设备地址 TargetAddress 24LC04
    说明I2C在总线上支持N-2-N,因此需要用地址来区分设备。一次完整的传输,总是START起始信号之后紧跟设备地址和读写标志。设备地址那么设备地址如何查看和定义的呢?设备地址对应第一个BYTE的BIT7-BIT1,BIT0对应读写标志I2C协议规定,除了0000XXX和1111XXX之外,其他地址均......
  • 『模拟赛』暑假集训CSP提高模拟4
    Rank一次比一次烂了,鉴定为不写模拟赛记录导致的。A.WhiteandBlack原题ARC148C被自己误导了,导致菊花和链的部分分没拿到。经验++对于每个点的父节点若有$1\lef_i\lti$,则该图构成的菊花图根可能为\(1\)或\(2\),链则不确定首尾。Subtask越来越不好判了www思......
  • NSSCTF———Web(sql注入)
    [LitCTF2023]这是什么?SQL!注一下![SWPUCTF2022新生赛]ez_sql[GXYCTF2019]BabySqli                                     点击右下角文章可跳转[LitCTF2023]这是什么?SQL!注一下!首先我们打开......
  • 解决: Cannot load information for github.com
    问题在共享项目至idea时候出现:IamgettingthiserrorwhilesharingonGithHubinIntellijeIDEA:Cannotloadinformationforgithub.com/:Requestresponse:Accesstothissitehasbeenrestricted.Ifyoubelievethisisanerror,pleasecontacthttps://suppor......
  • LLM-01 大模型 本地部署运行 ChatGLM2-6B-INT4(6GB) 简单上手 环境配置 单机单卡多卡
    搬迁说明之前在CSDN上发文章,一直想着努力发一些好的文章出来!这篇文章在2024-04-1710:11:55已在CSDN发布写在前面其他显卡环境也可以!但是最少要有8GB的显存,不然很容易爆。如果有多显卡的话,单机多卡也是很好的方案!!!背景介绍目前借到一台算法组的服务器,我们可以查看一下......
  • springsecurity使用:登录与校验
    首先是引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>默认方案:首次使用这个空项目的时候他会给你一个默认的账号账号名为user密码在控......
  • GGR273Smart Cities Bike Sharing Locations
    GGR273Lab1:SmartCities–BikeSharingLocationsLab 1:Analyzing BicyclingParking Locations inToronto(15%)Due:July 19th 2024@ 11:59 pm ESTthroughtheQuizzestabSubmitthrough Lab 1and answerquestionsandsubmitfile(.jpeg ofyour......