C#语言的从控制台输入输出是很麻烦的,特别是输入数字。因为C#语言只能读取字符(串),需要使用parse()方法转换为数字才行。所以C#一般不用于输入之类,比如程序设计类的比赛,一般用C,C++之类,而不用C#。
一:
1.输出:
Console.WriteLine()//输出来的换行
Console.Write()//输出来的不换行
2.字符串及其部分成员:
String num;
num = Console.ReadLine();
Console.WriteLine(num);
string str = "sicnu.com";
Console.WriteLine(str.Contains("s") + " " + str.Contains("h"));//加号代表拼接
Console.WriteLine(str.ToUpper()+str);
3.一维数组定义(3种方法):
int[] array1 = { 1, 2, 3, 4, 5 };
int[] array2 = new int[5] { 2, 2, 4, 4, 5 };
int[] array3 = new int[5];
输出数组(2种方法):
for (int i = 0; i < array1.Length; i++)
{
Console.WriteLine(array1[i]);
}
foreach (int i in array2)
{
Console.WriteLine(i);
}
4.二维数组及其输出:
int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } }; //2行三列
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(a[i, j]);
}
Console.WriteLine();
}
foreach (var item in a)
{
Console.WriteLine(item);
}
5.布尔类型:
bool a = false;
bool b = true;
if (a == b) Console.WriteLine("yes");
else Console.WriteLine("no!");
二:
1.类和构造函数、析构函数:
类:类是对数据和处理数据的方法(函数)的封装。类是对某一类具有相同特性和行为的事物的描述。
类的声明:
属性 类修饰符 class 类名{类体}
构造函数:
函数名 () {函数体}
函数名和类同名,无返回值
析构函数:
~类名 () {函数体}
无返回类型,也无参数
例:
class Student
{
public string name;
public string IDName;
public byte className;
public Student(string name, string IDName,byte className)//构造函数
{
this.name=name;
this.IDName=IDName;
this.className=className;
}
public Student()//构造函数的重载
{
name = "张三";
IDName = "12345678";
className = 1;
}
~Student()//析构函数
{
Console.WriteLine("析构函数");
}
}
2.封装:
封装 被定义为"把一个或多个项目封闭在一个物理的或者逻辑的包中"。
C# 封装根据具体的需要,设置使用者的访问权限。
class FZ
{
//private、public、protected、internal、protected internal为访问修饰符
int a1 = 4;//默认是private,封装性
private int a2 = 5;//对象本身在对象内部可以访问;
public int a3 = 6;//所有对象都可以访问;
protected int a4 = 7;//只有该类对象及其子类对象可以访问;
internal int a5 = 8;//同一个程序集的对象可以访问;
protected internal int a6 = 9;//访问限于当前程序集或派生自包含类的类型。
}
3.属性:
修饰符 类型 属性的名字
{
set{
//set代码
}
get{
//get代码
}
}
属性的本质就是外界访问私有字段的入口,本身就是方法,通过get方法和set方法对私有字段进行操作。
使用属性更方便,代码的结构也更合理
优点:
设置属性的set块和get块的有无,可以设置对私有字段的只读或只写。
通过改变set块或者get块的修饰符,设置本地可读外界不可读的(或本地可写,外界不可写)的情况。
4.方法:
方法类似于函数。
方法是依附于类和结构存在的函数;函数却是可以单独存在的。
方法定义:
访问修饰符 重写类型 返回类型 MethodName(参数)
{
方法主体;
}