构成C#语言的基本元素
- 关键字(KeyWord)
C#语言文档所定义的关键字 - 操作符(Operator)
C#语言文档所定义的操作符 - 标识符(Identifier)
- 什么是合法的标识符
①不能是关键字,若非要使用关键字重名,前面必须加@
②标识符必须以字符或者下划线来开头 - 大小写规范
- 命名规范
C#语言中变量名一般使用骆驼法(首单词小写后面单词首字母大写myForm)
名称空间名,类名,方法名一般使用pascal法(所有单词首字母大写MyForm)
- 什么是合法的标识符
- 标点符号
- 文本(字面值)
- 整数
- 多种后缀
- 实数
- 多种后缀
- 字符
- 字符串
- 布尔
- 空(null)
- 整数
class Program
{
static void Main(string[] args)
{
int a = 2;
long b = 3L;
float c = 3.0F;
double d = 4.1D;
char e = 'A';
string f = "ABC";
bool g = true;
string str = null;
}
}
- 注释与空白
- 单行
- 多行
初识类型,变量,方法
- 初识类型(Type)
- 亦称数据类型(Data Type)
class Program
{
static void Main(string[] args)
{
var a = 2L;
Console.WriteLine(a.GetType().Name);//获取变量类型
}
}
- 变量是存放数据的地方,简称“数据”
- 变量的声明
- 变量的调用
- 程序=数据+算法
- 有了数据和方法就可以写有意义的程序了
namespace IdentifierExample
{
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
int x = c.Add(2, 3);
Console.WriteLine(x);
string y = c.Today();
Console.WriteLine(y);
c.Sum(2,3);
}
}
class Calculator
{
public int Add(int a,int b)
{
int result = a + b;
return result;
}
public string Today()
{
int day = DateTime.Now.Day;
return day.ToString();
}
public void Sum(int a,int b)
{
int result = a + b;
Console.WriteLine(result);
}
}
}
算法简介
- 循环
- 递归
- 计算1到100的和
两种方法打印数字:
namespace IdentifierExample
{
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
c.Print1To10(10);
c.Print1To3(3);
}
}
class Calculator
{
public void Print1To10(int x)//循环打印1到10
{
for (int i = x; i > 0; i--)
{
Console.WriteLine(i);
}
}
public void Print1To3(int x)//递归打印1到3
{
if (x == 1)
{
Console.WriteLine(x);
}
else
{
Console.WriteLine(x);
Print1To3(x - 1);
}
}
}
}
两种方法计算1到100的和:
namespace IdentifierExample
{
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
int x = c.Sum1To100_xunhuan(100);
int y = c.Sum1To100_digui(100);
Console.WriteLine(x);
Console.WriteLine(y);
}
}
class Calculator
{
public int Sum1To100_xunhuan(int x)
{
int result = 0;
for (int i = 1; i < x + 1; i++)
{
result = result + i;
}
return result;
}
public int Sum1To100_digui(int x)
{
if (x == 1)
{
return 1;
}
else
{
int result = x + Sum1To100_digui(x - 1);
return result;
}
}
}
}