打算学下unity3d,先学点c#基础
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;//读写文件
using Newtonsoft.Json.Linq;//json的dll
using System.Threading;//sleep
using System.Net;//发送http请求的包
using System.Text;//发送http请求的包,拼接字符串用的
//using System.Threading.Tasks;
namespace cs0312
{
class BaseExample
{
public string tips;
public BaseExample()
{
this.tips = "自动加载了BaseExample类的构造方法";
}
public void Add()
{
Console.WriteLine(tips);
}
public virtual void GetConfig()
{
Console.WriteLine("这个方法将被继承的时候重写");
}
public void Dalao(string name)
{
Console.WriteLine(name + "大佬你好!");
}
public void Daojishi()
{
for (int i = 2; i > 0; i--)
{
Console.WriteLine("倒计时" + i + "秒");
Thread.Sleep(1000);//休眠0.1秒
}
}
}
class Index : BaseExample//只能继承一个类,不能多个继承
{
public string city;
public override void GetConfig()
{
//子类调用符类的方法用base,类中调用用this
this.city = "深圳的";
base.Dalao(city + "马老板");
Console.WriteLine("override跟virtual是成对出现的,这个方法将重写继承的BaseExample父类的GetConfig()方法");
}
public void TestExtend()
{
Console.WriteLine("IndexClass的TestExtend方法");
}
//获取时间,返回时间戳
public Int64 NowTimeInt()
{
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
public static string NowTimeStr(string format = "")
{
if (format == "")
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
return DateTime.Now.ToString(format);
}
}
public static void ExecJob(object state)
{
Console.WriteLine(Index.NowTimeStr());
}
public static void Yinyong(ref string x)//ref表示按引用传值
{
x = "ref是引用传值"+DateTime.Now.ToString();
}
}
class Program
{
static void Main(string[] args)
{
//按引用传值
string anyinyong = "ref是引用传值";
Index.Yinyong(ref anyinyong);//函数引用传值
Console.WriteLine(anyinyong);
//short取值范围-32768到+32767,两个字节,int是有符号的正负21亿,unit是无符号的
short shNum = 32767;//long是 int64, float是占4字节, double8字节双精度
ushort ushNum = 65535;//ushort取值是mysql的smallint 65535
long int64Num = 9223372036854775807;//占8个字节
long yearNum = (long)86400*365*100000000;
long longres = int64Num / yearNum;
Console.WriteLine("每秒插入一亿条数据,可以插入年数是:"+ longres);
const int mysqlPort = 36635;//声明常量,语法const+类型+常量名称 = 数值,常量声明后不能更改数值
//return;
//执行定时器的任务,windows的时间精度是15毫秒,小于15就是15
//需要注意的是TimerCallback()的函数必须传入ExecJob(object state),不然是不行的哦!
//需要十分注意,如果上一次的任务还没有执行,又创建了新的任务会并行执行可能会出问题的
//所以任务在进入的时候就要更改执行中的状态,所以公共的数据要加锁
//new Timer(new TimerCallback(Index.ExecJob),null,500,1000)
//Index.ExecJob执行的回调函数,null是任务对象,500毫秒后开始执行(0.5s),周期是1000毫秒(1s)
Timer timer = new Timer(new TimerCallback(Index.ExecJob), null, 1000, 1000);
//Console.ReadLine();//阻塞起来,下面的代码就无法运行下去了
//发送http请求
Dictionary<string, string> postPrams = new Dictionary<string, string>();
postPrams["data"] = "Denny";
postPrams["time"] = Index.NowTimeStr();
postPrams["rid"] = "fromCsPost";
dynamic curlBody = HttpCurl.Post("https://www.buruyouni.com/spider/request", postPrams);//?rid=shutdownd&data=
Index ind01 = new Index();
Int64 nowTimeStamp = ind01.NowTimeInt();//时间戳数字
Console.WriteLine("消耗时间秒:" + nowTimeStamp + "类型是:" + nowTimeStamp.GetType());
//datetime时间日期 2021-03-07 23:42:37 2021-03-07 2021
Console.WriteLine("时间字符串:" + Index.NowTimeStr() + " 自定义时间格式:" + Index.NowTimeStr("yyyy年MM月dd") + ",年份:" + Index.NowTimeStr("yyyy"));
for (Int64 i = 0; i < 999; i++)//999999999
{
}
Int64 useSecond = ind01.NowTimeInt() - nowTimeStamp;
Console.WriteLine("循环消耗时间秒:" + useSecond);
float fff = 3.13f;//声明浮点数要后面加f,所以
double doubleNum = 3.14;//声明有小数的可以用double,判断字符类型
Console.WriteLine("双精度浮点数:" + doubleNum + ",类型是:" + doubleNum.GetType());
dynamic resPlus = fff + doubleNum;
resPlus = Math.Round(resPlus, 2);//4舍五入保留两位小数,2就是保留两位
int downInt = (int)6.66;//向下取整
double upInt = Math.Ceiling(6.66);//向下取整,获取到的是double
double downDouble = Math.Ceiling(6.66);//向下取整,获取到的是double
Console.WriteLine("6.66使用Math.floor()向下取整:" + downDouble + ",数值6.66Math.Ceiling()向上取整:" + upInt);
int i6 = 7;//int跟double的值比较
Console.WriteLine("double 7 ==int 7的值比较" + (i6 == upInt));
//Equals判断全等,先判断类型,再判断值.i6是int,upInt是double是不全等的
Console.WriteLine("全等double 7和int 7的Equals全等比较:" + i6.Equals(upInt));
Console.WriteLine("float的数和double的数相加:" + resPlus + ",取整:" + downInt + ",向上取整:");
dynamic atStr = "dynamic可以动态声明变量类型,可以是各种类型int,double,folat等";
Console.WriteLine(atStr + "支持三木," + (atStr != "" ? true : false));
BaseExample be = new BaseExample();
Thread tt = new Thread(new ThreadStart(be.Daojishi));
tt.Start();//开始执行,这里be.Daojishi无阻塞,下面的不用等待直接执行
//tt.Join();//阻塞,等待子线程执行完毕再执行下面的代码,如果不加tt.Join下面的代码不需要等待子线程的结束直接执行
//using Newtonsoft.Json.Linq;生成json字符串
JObject j = new JObject();
j["id"] = 20210308;
j["name"] = "张无忌";
string jString = j.ToString();
Console.WriteLine("使用github的Newtonsoft.Json.dll生成json字符串" + jString);
//解析刚才生成的json字符串jString
JObject jp = JObject.Parse(jString);
//判断json的字段是否存在
if (jp.ContainsKey("name"))
{
string nameStr = (string)jp.GetValue("name");
Console.WriteLine("存在key=name的json对象值是:" + nameStr);
}
if (jp.ContainsKey("id"))
{
int jid = (int)jp.GetValue("id");
Console.WriteLine("存在key=id的json对象值是:" + jid);
}
//如果文件目录(文件夹)不存在则创建
string activeDir = @"E:/cs";//创建e:/cs/myCreateDir文件夹
string newPath = System.IO.Path.Combine(activeDir, "myCreateDir");
System.IO.Directory.CreateDirectory(newPath);
//1.实例化文件类,fileinfo需要using System.IO;
FileInfo fi = new FileInfo("e:/cs/aaa.txt");
//2.打开文件流(读取方式)
FileStream stm = fi.OpenRead();
//读取文件(一次性读取)
long fileSize = fi.Length;//查看文件大小
byte[] buffer = new byte[fileSize];
int n = stm.Read(buffer, 0, buffer.Length);
Console.WriteLine("读取到的文件数据:" + n + fi.Attributes.ToString());
//关闭文件流
stm.Close();
//字符串分割
string spString = "jpg,jpeg,png,gif";
string[] sArray = spString.Split(",");
//遍历字符串分割后的数组
foreach (string i in sArray)
{
Console.WriteLine(spString + "分割成:" + i);
}
//项目引用外部的dll文件,实例化命名空间MyFirstDll下的Class1类
//MyFirstDll.Class1 fdl = new MyFirstDll.Class1(); ;
//fdl.Author();
//异常处理
try
{
//try结果
}
catch (Exception e)
{
//发生异常处理
}
myextend.Mynamespace ms = new myextend.Mynamespace();
ms.UseAnotherDirClass("调用其他文件夹的类的方法");
//UseAnotherDirClass
//事件委托和回调
ColorBox box = new ColorBox();
//1.注册回调,回调执行的方法是box类的OnClolorChanged()
box.UserHandler = new ColorBox.ChangeHandler(box.OnClolorChanged);
//2.方法触发用户回调UserSelect();
box.UserSelect("触发回调");
//泛型,Dictionary即key:value需要引入using System.Collections.Generic;
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("name", "dwj");
//dic.Add("name", "dwj2");//dic的key不能重复添加
dic.Add("age", "18");
dic.Add("sex", "小姐姐");
//这种方式添加key=name的数据,存在就覆盖,不存在就添加
dic["name"] = "覆盖上面的add方法添加的key,建议用这种方式添加,add添加如存在了会抛出异常!";
Console.WriteLine("dic的数量是:" + dic.Count);
//判断name这个Key是否存在dic里面,如果key不存在则必须判断是否存在
if (dic.ContainsKey("name"))
{
Console.WriteLine("key=name存在dic,数值是:" + dic["name"]);
}
dic.TryGetValue("sex", out string getVal);
Console.WriteLine("dic.TryGetValue()可以取存在或者不存在的key" + getVal);
List<int> fanxing = new List<int>();
fanxing.Add(10);
fanxing.Add(20);
fanxing.Add(30);
for (int i = 0; i < fanxing.Count; i++)
{
Console.WriteLine(string.Format("for 遍历list 第{0}个输的值是:{1}", i, fanxing[i]));
}
//官方推荐foreach遍历,不支持一边遍历一边删除惭怍,都是只读遍历
foreach (int item in fanxing)
{
Console.WriteLine(string.Format("foreach 遍历list 第{0}个输的值是:", item));
// i= i+1;
}
//枚举遍历
//类的继承,
Index ic = new Index();
BaseExample ic02 = new Index();
ic.Add();
ic.GetConfig();//overide/Virtual重写符类方法
ic02.GetConfig();//ic02指定了BaseExample符类
string hello = "Hello World!!!!!";
Console.WriteLine(hello);
int a = 10;
int b = a * 3;
Console.WriteLine("a=10乘以3=" + b);
//字符串拼接数字
string name = "杨兴毅,age=" + (a + 20);
Console.WriteLine(name);
//字符串格式化
string placeStr = string.Format("中国:{0}省:{1}", "广东", "佛山");
Console.WriteLine(placeStr);
//实例化Student类,默认加载Student构造方法
Student stu = new Student();
//cs不用管垃圾回收,当没人用它的时候会自动销毁
//实例化Student类,加载Student(bool)构造方法,构造方法也可以重载
Student stu02 = new Student(true);
stu.id = 1000;
stu.name = "Denny Young";
stu.sex = true;
Console.WriteLine("ID:{0},名字:{1},性别:{2}", stu.id, stu.name, stu.sex ? "男" : "女");
Console.WriteLine("打印stu对象成字符串:" + stu.ToString());
//cs支持GetName方法名一样,但是参数不一样的函数在同一个类中
//类的方法支持大小写开头,不过推荐用大写开头,go大写则是公共方法,小写是私有方法
Myexample example = new Myexample();
example.GetName();
example.GetName(999);
//类的拆分在不同文件,public partial class xx
Chaifen cf = new Chaifen();
cf.C01();//调用当前文件的Chaifen类的方法
cf.C02();//调用student.cs文件的Chaifen类的C02方法
}
}
public class ColorBox
{
//1.定义事件委托类型
public delegate void ChangeHandler(string colorString);
//2.定义回调
public ChangeHandler UserHandler;
//3.模拟用户选择,选择后触发回调
public void UserSelect(string selectColor)
{
if (UserHandler != null)
{
//Invoke()执行
UserHandler.Invoke(selectColor);
}
}
//4.选择后触发回调
public void OnClolorChanged(string colorStr)
{
Console.WriteLine("回调选用了颜色:" + colorStr);
}
}
public partial class Chaifen
{
public void C01()
{
Console.WriteLine("类拆分在不同文件Program.cs,Chaifen类的C01()方法");
}
}
class HttpCurl
{
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url, Dictionary<string, string> dic)
{
string result = "";
//using System.Net;引入http请求的包
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//region 添加Post 参数
StringBuilder builder = new StringBuilder();//引入Text包using System.Text;
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
//endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
}
}