类, 结构体, 继承, 接口
- C# 实现多态: 父类方法要有’virtual’关键字, 子类方法有’override’
- struct 不能继承class但能继承接口.
- struct , class 都默认继承object
- Class 最多继承一个类
- 关键字: interface , abstract 用法于Java类似
基类object的方法:
常用数据结构 , 泛型 , 反射 , 宏(具体方法可以在官方文档中查找)
- Array: 固定长度[] , length 取得长度
- List : 动态数组 , 自动增长.
- Dictionary (字典) :使用key , 来获取value
- HashSet :保证里面的元素是唯一的
- Queue : 可动态增长 , 先进先出 (Enqueue方法进列, Dequeue 方法出列)
- Stack : 可动态增长 , 先进后出 (Push入栈 , Pop出栈)
函数指针
反射( Attribution )
类型信息,变量,函数 本质上是获取代码信息
内容总结:
异常 , 操作符号重载
- C#的异常机制于Java类似,
- 操作符可以重载 要定义为 : public static 返回类型 operator 符号名 (参数1,参数2)
- 操作符重载可以重载下标 要定义为: public 返回类型 this[int index]
综合实例: 简单计算器
using System;
namespace SimpleCalFinal
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入题目 : ");
String inputStr = Console.ReadLine();
CaclOneLine(inputStr);
}
}
public class CalcInfo
{
public string tag;
public Func<float, float, float> func;
public CalcInfo(string tag,Func<float,float,float> func)
{
this.tag = tag;
this.func = func;
}
}
static CalcInfo[] configs = new CalcInfo[]
{
//定义一个数组
new CalcInfo("+" ,(a,b)=> a + b),
new CalcInfo("-" ,(a,b)=> a - b),
new CalcInfo("*" ,(a,b)=> a * b),
new CalcInfo("/" ,(a,b)=> a / b)
};
private static void CaclOneLine(string inputStr)
{
int index = -1;
Func<float, float, float> func = null;//函数指针
//一个一个试, 直到正确匹配tag 后赋值给函数指针
for(int i = 0; i < configs.Length; i++)
{
var item = configs[i];
index = inputStr.IndexOf(item.tag);
if(index != -1)
{
func = item.func;
break;
}
}
if(index == -1)
{
Console.WriteLine("当前只支持 + - * / 运算");
return;
}
CallcResult(inputStr, func, index);
}
private static void CallcResult(string inputStr, Func<float, float, float> func, int index)
{
string numStr1 = inputStr.Substring(0, index);
int strLen = inputStr.Length;
string numStr2 = inputStr.Substring(index + 1, strLen - index - 1);
float num1 = float.Parse(numStr1);
float num2 = float.Parse(numStr2);
float result = func(num1, num2);
Console.WriteLine($"{inputStr}的计算结果是: {result}");
}
}
}
运行结果: