本博客内容正在持续更新,最后一次更新时间:2020.08.05
【本文重点】
(待完成)
1 Basic
1.1 数据类型 ---- Value & Reference type
1.1.1 Value type
对于 value type 的数据,用等号做赋值运算时,相当于创建了一个新的对象
int, double …
1.1.2 Reference type
对于 reference type 的数据,用等号做赋值运算时,等号左右两个变量名依旧指向同一个对象(和 Python 一致),即若有 A = B,在改变 A 的同时还会改变 B
List …
List<double> numbers = new List<double>() {0.1, 0.2};
// 增加
numbers.Add(0.3);
1.2 逻辑语句
1.2.1 foreach Loop
foreach(double number in numbers) {
// do something with number
}
1.3 函数
double myAdder(double a, double b) {
double c = a + b;
return c;
}
1.3.1 Notes
1.不同函数的函数名可以是同一个,但是输入变量的数目以及类型不能完全一致
正确示例:
double myFunc(double a, double b) {}
double myFunc(double a, int b) {}
错误示例:
double myFunc(double a, double b) {}
double myFunc(double c, double d) {}
2.用函数改变外部 value type & reference type 的变量
(关于这两个 type 的具体说明请查阅 Section 1.1)
改变外部 value type 的变量需要在 type 前添加 ref
int n = 1; int m = 1;
List<int> N = new List<int>() { };
addVal(n); // >> 输出 n = 1
addValInRef(ref m); // >> 输出 m = 2
addRef(N); // >> 输出 N = [1]
static void addVal(int a) {
a = a + 1;
}
static void addValInRef(ref int a) {
a = a + 1;
}
static void addRef(List<int> A) {
A.Add(int a = 1);
}
Example: 将半径为 r(输入) 的圆的面积,赋值给初始定义的一个变量
double circleArea = 0.0;
getCircleArea(double r, ref circleArea);
static void getCircleArea(double r, ref circleArea) {
circleArea = 3.14 * Math.Pow(r, 2);
}
1.4 Random
1.Random Generator
Random myRandomGenerator = new Random();
2.get random number
取 [0.0, 1.0) 间的随机浮点数
double rd1 = myRandomGenerator.NextDouble();
取 [0.5, 2.5) 间的随机浮点数
double rd2 = myRandomGenerator.NextDouble() * 2.0 + 0.5;
取 [5, 15) 间的随机整数
int ri = myRandomGenerator.Next(5, 15);
3.set seed 设置种子
种子可以固定生成的随机数,无论 rebuild 多少次都会生成一样的随机数
Random myRandomGenerator = new Random(0);
double a = myRandomGenerator.NextDouble();
double b = myRandomGenerator.NextDouble();
2 Class
class MyClass
{
}
2.1 构造函数
在创建类对象时,构造函数被用于参数的传入
- 构造函数没有 return
- 可以定义多个同名构造函数(参数不能一样)
class MyClass
{
public int A;
public MyClass(int a)
{
A = a;
}
public MyClass()
{
A = 555;
}
}
MyClass mc1 = new MyClass(666);
MyClass mc2 = new MyClass();
Console.WriteLine(mc1.A.ToString())
Console.WriteLine(mc2.A.ToString())
666
555
2.2 public and private
用 public 修饰的变量可以从外部直接修改和访问,而用 private 修饰的则间接修改和访问。 因此用 private 修饰变量可以避免一些错误的发生:如下,避免了从外部把长度修改为负数值
class Square
{
private double length;
public double Length
{
get { return length; }
set
{
if (value > 0.0)
length = value;
else
length = 0.0'
}
}
1.直接修改和访问 length,报错
Square s = new Square();
s.length = -1.0;
Concel.WriteLine(s.length.ToString());
Error Message: "length" is inaccessible due to its protection level
Error Message: "length" is inaccessible due to its protection level
2.通过 Length 间接修改 length,只能输入正数,否则无效
Square s = new Square();
s.Length = 1.0;
Concel.WriteLine(s.Length.ToString())
1.0
Visual Studio IDE 上的便利操作
1 修改全部同名变量
选中变量名后按 F2,或右键单击选择重命名
2 批量注释、取消注释
批量注释:Ctrl + K + C
批量取消注释:Ctrl + K + U