首页 / Unity3d / C#

读一读

//三种初始化方式
StringBuilder sb = new StringBuilder("strstrstr");
StringBuilder sb = new StringBuilder(length);
StringBuilder sb = new StringBuilder("str",length);

这里的length是临时的长度,当类容超过这个长度时,就会重新申请长度,长度的两倍


s.CompareTo("str") //相等返回0,大于返回1,小于返回-1
s.Replace('s','b')  //将s换成b,返回新的字符串
string[] arr = s.Split('.');  //以给定字符切分字符串为字符串数组
s.Substring(startIndex,length);  //截取指定位置的子字符串为新的字符串

FileStream fs = new FileStream(File_Name,FileMode.Open,FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
r.ReadString();
r.Close();
fs.Close();

using(StreamReader sr = File.OpenText(File_Name)){
    string input;
    while((input = sr.ReadLine()) != null){
        Console.WriteLine(input);
    }
    sr.Close();
}

using(StreamWriter w = File.AppendText("test.txt")){
    Log("hehe",w);
    w.close();
}

public void static Log(string logMessage,TextWriter w){
    w.Write("\r\nLog Entry:");
    w.WriteLine(":{0}",logMessage);
    w.Flush();
}

文件操作或数据库连接等比较消耗资源的操作,使用using在结束时自动释放


FileStream fs = new FileStream(File_Name,FileMode.Create);
BinaryWriter w = new BinaryWrite(fs);
w.write("a");
w.close();
fs.close();

FileMode中有:

Open,文件不存在报错

OpenOrCreate,打开或创建

Appent,追加


DirectoryInfo dir = new DirectoryInfo(Path);//针对某一个文件夹的信息
foreach(FileInfo f in dir.GetFiles("*.exe")){
    //f.Name 文件名字
    //f.Length 这是啥
    //f.CreationTime 文件创建时间
}

File和Directory是静态类

using System.IO;
File.Exists(@"C:\1.txt");//判断文件是否存在
Directory.Exists(路径);//判断文件夹是否存在

List<int> list = new List<int>(20);

public int this[int index] {
    get {
        if (index < 0) {
            index = 0;
        }

        if (index > 19) {
            index = 19;
        }

        return list[index];
    }

    set {
        if (index < 0)
        {
            index = 0;
        }

        if (index > 19)
        {
            index = 19;
        }

        list[index] = value;//value就是赋值的数据
    }
}

索引器使用前,那个集合必须先要初始化了

就是使用Add方法添加元素,不能通过索引赋值的方式添加元素


泛型类

class A<T>{
    public T a;
}

创建对象时需要指定T的类型

A<int> obj = new A<int>();//int就会替代调T


泛型方法

static T Add<T>(T a,T b){}

有时候,父类是拥有多个构造函数的

所以在编写子类构造函数需要指定使用父类的哪个构造函数

public 构造函数(参数a):base(参数a){}