C#快速入门
自己看视频写的代码,记录一下
上面注释是测试代码,下面注释的是测试 所用到的类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
#region 测试代码
/*
Console.WriteLine("Hello World!");
Console.WriteLine("我的名字是{1}","zhw","zdd");
Student student = new Student("zhw", 22);
student.Show();
* 测试StringBuilder执行效率
* Stopwatch 计时器 = new Stopwatch();
计时器.Start();
string str = string.Empty;
for(int i = 0; i < 10000; i++)
{
str += i.ToString();
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 100000; i++)
{
sb.Append(i.ToString());
}
计时器.Stop();
Console.WriteLine(计时器.ElapsedMilliseconds);
//字符串转大写
String str1 = "abc";
Console.WriteLine(str1.ToUpper());
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
AddNum(a, b);
//斐波那契数列
int[] a = new int[10];
a[0] = 1;
a[1] = 1;
for (int i = 2; i <= a.Length - 1; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
for(int j = 0; j < a.Length; j++)
{
Console.WriteLine(a[j]);
}
//选择排序
int temp;
int[] a = {3,4,1,2,6,5 };
for(int i = 0; i < a.Length; i++)
{
for(int j = i+1; j < a.Length; j++)
{
if (a[i] > a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
foreach(int x in a)
{
Console.WriteLine(x);
}
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
Console.WriteLine(Average(list));
//统计文件或目录的个数
Console.WriteLine("正在统计中 ...");
Console.WriteLine(FileOrDirCount("E:\\q"));
//多态和接口
Dog dog = new Dog("小黑",12);
dog.shout();
Bird bird =new Bird("小小鸟", 5);
bird.Fly();
//结构体
Location loc = new Location(2, 3);
Console.WriteLine(loc.X);
//枚举
ConnectionState con = new ConnectionState();
con = ConnectionState.Disconnected;
switch (con)
{
case ConnectionState.Connecting:
Console.WriteLine("正在连接中...");break;
case ConnectionState.Connected:
Console.WriteLine("连接成功..."); break;
case ConnectionState.Disconnecting:
Console.WriteLine("断开连接中..."); break;
case ConnectionState.Disconnected:
Console.WriteLine("已断开连接..."); break;
}
//使用using关闭文件流
Console.WriteLine("before using");
using(var sr=new StreamReader("temp.txt"))
{
Console.WriteLine(sr.ReadToEnd());
}
Console.WriteLine("after using");
//委托
//添加委托方式
Traverse(new List<int>() { 1, 2, 3, 4, 5, 6 },IsEven);
//简化添加委托方式(Lambda表达式)
//Traverse(new List<int>() { 1, 2, 3, 4, 5, 6 }, delegate (int n) { return n % 2 == 0; });
//Traverse(new List<int> { 1, 2, 3, 4, 5 }, (int num) => { return num % 2 == 0; });
//Traverse(new List<int> { 1, 2, 3, 4, 5 }, (num) => { return num % 2 == 0; });
//Traverse(new List<int> { 1, 2, 3, 4, 5 }, num => { return num % 2 == 0; });
//Traverse(new List<int> { 1, 2, 3, 4, 5 }, num => num % 2 == 0);
//多播委托
all = AddThenPrint + Print;
all -= Print;
all(1);
//LINQ
IEnumerable query=
from filename in Directory.GetFiles("D:/")
let fileinfo=new FileInfo(filename)
orderby fileinfo.Length descending
select new { fileinfo.Name};
var n = query.GetEnumerator();
while (n.MoveNext())
{
Console.WriteLine(n);
}
//反射
var temp = new Temp();
var input = Console.Read();
//利用反射创建类
//var instance = Assembly.Load("ConsoleApp1").CreateInstance("ConsoleApp1." + input);
//var function = instance.GetType().GetMethod(input);
//function.Invoke(instance, null);
var type1 = typeof(Temp);
var pro = type1.GetProperty("name");
pro.SetValue(temp, "aaa", null);
var fun = type1.GetMethod("Fun");
fun.Invoke(temp, new object[] {1 });
//序列化
var temp = new Temp();
using(var stem = File.Open(typeof(Temp).Name + ".txt", FileMode.Create))
{
var bf = new BinaryFormatter();
bf.Serialize(stem, temp);
}
//反序列化
Temp after = null;
using (var stem = File.Open(typeof(Temp).Name + ".txt", FileMode.Open))
{
var bf = new BinaryFormatter();
after=(Temp)bf.Deserialize(stem);
}
Console.WriteLine(after.name);
//线程与同步
var task1 = new Task(() => {
for(int i = 0; i < 500; i++)
{
Console.Write("+");
}
});
var task2 = new Task(() => {
for (int i = 0; i < 500; i++)
{
Console.Write("-");
}
});
task1.Start();
task2.Start();
task1.Wait();
task2.Wait();
//串行与并行
var list = new List<int>() ;
for(int i = 0; i < 5000000; i++)
{
list.Add(i);
}
//串行处理
CalcTime(() => list.ForEach(i => i++));
//并行处理
CalcTime(() => list.AsParallel().ForAll(i => i++));
CalcTime(()=>Parallel.ForEach(list, i => i++)) ;
//同步与加锁
var task1 = new Task(Increment);
var task2 = new Task(Decrement);
task1.Start();
task2.Start();
Task.WaitAll(task1, task2);
Console.WriteLine(Count);
//其他
var dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
//正则表达式判断字符串是否为邮箱
if (IsValidEmail("14663@qq.com"))
{
Console.WriteLine("是邮箱");
}
else
{
Console.WriteLine("不是邮箱");
}
*/
#endregion
}
#region 测试类
/*
*
//其他
//正则表达式判断字符串是否为邮箱
static bool IsValidEmail(string str)
{
return Regex.IsMatch(str, @"^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$");
}
//线程与同步
//串行与并行
//计算程序执行时间
static void CalcTime(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
//同步与加锁
//创建锁
private static readonly object Syn = new object();
static int Count = 0;
static void Increment()
{
for(int i = 0; i < 5000000; i++)
{
lock (Syn)//加锁
{
Count++;
}
}
}
static void Decrement()
{
for(int i = 0; i < 5000000; i++)
{
lock (Syn)//加锁
{
Count--;
}
}
}
* //序列化与反序列化
class Temp
{
[Serializable]
public string name = "123";
public void Fun(int a)
{
Console.WriteLine(a);
}
}
* //反射
class Temp
{
public string name { get; set; }
public void Fun(int a)
{
Console.WriteLine(a);
}
}
//自定义集合
class MyList : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
yield return 1;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
//扩展方法 必须在静态类中定义
static class MyExMethods
{
public static int MyCount(this IEnumerable<int> list)
{
int sum = 0;
var e = list.GetEnumerator();
while (e.MoveNext())
{
sum++;
}
return sum;
}
}
//委托
//多播委托
static Action<int> all;
static Action<int> AddThenPrint = i => { i++; Console.WriteLine(i); };
static Action<int> Print = i => Console.WriteLine(i);
//声明委托类型
delegate bool Function(int num);
//大于10的数
static Function GreaterThan10 = delegate (int num) {return num >= 10; };
//偶数
static Function IsEven = delegate (int num) { return num % 2 == 0; };
static List<int> Traverse(List<int> nums,Function function)
{
var list = new List<int>();
foreach(var num in nums)
{
if (function(num))
{
list.Add(num);
}
}
foreach(var i in list)
{
Console.WriteLine(i);
}
//遍历集合---------list.ForEach(i => { Console.WriteLine(i); });
return list;
}
class Test : IDisposable
{
public void Dispose()
{
Console.WriteLine("DISPOSING..");
}
}
//枚举
enum ConnectionState //连接状态
{
Connecting,//正在连接
Connected,//连接成功
Disconnecting,//断开连接中
Disconnected,//已断开连接
}
//结构体
struct Location
{
public int X;
public int Y;
public Location(int X, int Y)
{
this.X = X;
this.Y = Y;
}
}
//类,多态和接口
class Animal
{
public string name { get; set; }
public int age { get; set; }
public Animal(string name, int age)
{
this.name = name;
this.age = age;
}
public void show()
{
Console.WriteLine("名字:" + this.name + "年龄:" + this.age);
}
}
interface IFly
{
void Fly();
}
class Dog : Animal
{
public Dog(string name, int age) : base(name, age) { }
public void shout()
{
this.show();
Console.WriteLine("汪汪汪...");
}
}
class Cat : Animal
{
public Cat(string name, int age) : base(name, age) { }
public void shout()
{
this.show();
Console.WriteLine("喵喵喵...");
}
}
class Bird : Animal, IFly
{
public Bird(string name, int age) : base(name, age) { }
public void Fly()
{
Console.WriteLine("I want fly");
}
public void shout()
{
this.show();
Console.WriteLine("叽叽叽...");
}
}
static long FileOrDirCount(string path)
{
long count = 0;
try
{
//统计file的个数
var files = Directory.GetFiles(path);
count += files.Length;
//统计directory的个数
var dirs = Directory.GetDirectories(path);
count += dirs.Length;
foreach (var dir in dirs)
{
count += FileOrDirCount(dir);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return count;
}
static double Average(List<int> list)
{
int sum = 0;
foreach (int i in list)
{
sum += i;
}
return (double)sum / list.Count;
}
public static void AddNum(int a, int b)
{
Console.WriteLine(a + b);
}
}
class Student
{
private String name;
private int age;
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public void Show()
{
Console.WriteLine("我的名字是:" + this.name + "我的年龄为:" + this.age);
}*/
#endregion
}
}