ref
通过加关键词ref使得基本类型变为传引用:
// 定义
void deal(ref int a){}
// 使用
deal(ref a)
只读
定义时使用get
public string title { get; } = "";
值得注意的是,虽然不能直接赋值,但是却可以调用其成员函数来达到修改的效果。
override
基类的函数前加上virtual后继承类即可通过override重写,通过base.function()调用基类的方法。
class Program
{
static void Main(string[] args)
{
O o = new O();
o.use();
Console.WriteLine(o.a);
// 输出6
}
}
public class Base
{
public int a = 0;
virtual public void use()
{
a += 2;
}
}
public class O : Base
{
public override void use()
{
base.use();
a += 4;
}
}
比较容易搞混的是继承类的构造方法会自行调用基类的无参的构造方法:
class Program
{
static void Main(string[] args)
{
O o = new O();
Console.WriteLine(o.a);
// 输出3
}
}
public class Base
{
public int a = 0;
public Base()
{
a += 1;
}
}
public class O : Base
{
public O()
{
a += 2;
}
}
foreach和remove
在List<>的foreach过程中remove会出问题,正确方法是:
for(int i=0;i<L.Count;i++)
{
Obj o = L[i];
if (...)
{
L.RemoveAt(i);
i--;
}
}
delegate
https://www.cnblogs.com/vaevvaev/p/6907782.html
yield
https://blog.csdn.net/u013477973/article/details/55804729
https://blog.csdn.net/fdyshlk/article/details/80215192
yield return null;
// 下一帧再执行后续代码
yield return 0;
//下一帧再执行后续代码
yield return 6;
//(任意数字) 下一帧再执行后续代码
yield break;
//直接结束该协程的后续操作
yield return asyncOperation;
//等异步操作结束后再执行后续代码
yield return StartCoroution(/*某个协程*/);
//等待某个协程执行完毕后再执行后续代码
yield return WWW();
//等待WWW操作完成后再执行后续代码
yield return new WaitForEndOfFrame();
//等待帧结束,等待直到所有的摄像机和GUI被渲染完成后,在该帧显示在屏幕之前执行
yield return new WaitForSeconds(0.3f);
//等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的时间会受到Time.timeScale的影响);
yield return new WaitForSecondsRealtime(0.3f);
//等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的时间不受到Time.timeScale的影响);
yield return WaitForFixedUpdate();
//等待下一次FixedUpdate开始时再执行后续代码
yield return new WaitUntil()
//将协同执行直到 当输入的参数(或者委托)为true的时候....如:yield return new WaitUntil(() => frame >= 10);
yield return new WaitWhile()
//将协同执行直到 当输入的参数(或者委托)为false的时候.... 如:yield ret
协程
public IEnumerator Timer(float second)
{
while (second>= 0)
{
second-=1f;
if (second== 0)
{
Debug.Log("gameOver");
yield break;//停止协程
}
else if (second > 0)
{
yield return new WaitForSeconds(1);// 等待 1 秒
}
}
}
泛型
public void RandomShuffle<T>(List<T> L)
{
System.Random rd = new System.Random();
for(int i = 0; i < L.Count; i++)
{
int j = rd.Next(0, L.Count - 1);
swap(L[i], L[j]);
}
}
private void swap<T>(T t1, T t2)
{
T tmp = t1;
t1 = t2;
t2 = tmp;
}