首页 / Unity3d / C#

读一读

switch(变量){
    case 值:
        //操作
    break;
    .........
    default://以上情况斗没有发生
    break;
}

int i = num<100?num:99;
//如果num<100则赋值我num,否则赋值为99

static void Main(string[] args)
{
    Func<int, int, string> func = ReturnFunction;
    Console.WriteLine(func(1, 2));

    Console.ReadKey();
}

static string ReturnFunction(int a, int b) {
    return "a+b=" + (a + b);
}

Func通过指定泛型<T1,T2...Return>,前面指定参数的类型,最后一个指定返回的类型

Func对比Action就是它可以承载带返回的函数


//Action无返回值
static void Main(string[] args)
{
    Action<string> a = NormalFunc;
    a("Hei");

    Console.ReadKey();
}
        

static void NormalFunc(string str) {
    Console.WriteLine("I am NORMAL FUNCTION " + str);
}

Action是一个内置委托类型,通过泛型<T1,T2...>指定函数参数


using System.Diagnostics;
Stopwatch stopwatch = new Stopwatch();//就是这个类
stopwatch.Reset();//重置,不然会累计
stopwatch.Start();//开始计时
int res = getGYSByXJF2(a, b);//计算这个方法的用时
stopwatch.Stop();//停止计时
Console.WriteLine(res + " 用时:" + stopwatch.ElapsedMilliseconds);//毫秒计算

Random r = new Random();
int random_index = r.Next(0, 100);//包前不包后

static void Pri(params string[] strs) {
    foreach (string str in strs) {
        Console.WriteLine(str);
    }
}

Pri("hello", "i", "am");
string[] strss = { "you", "is", "me" };
Pri(strss);


params只能在最后一个参数上声明

作用就是声明一个参数(数组)后,可以传入多个这个类型的参数

可以不传参数,主要看函数怎么用这个参数


C#中所有引用类型都是直接继承自System.Object;而值类型是继承自System.ValueType,而System.ValueType还是继承自System.Object的,它没有添加任何方法,只是覆盖了一些方法,让它更适合值类型。


string[] panelNames = Enum.GetNames (typeof(UIPanelType));

返回一个字符串的数组,UIPanelType是一个枚举类型

Enum在System命名空间下


public static class Dict {

	public static tValue tryGet<tType,tValue>(this Dictionary<tType,tValue> dict,tType t)
	{
		tValue v;
		dict.TryGetValue (t, out v);
		return v;
	}
}

Dictionary<UIPanelType,BasePanel> uiPanelScriptDict = new Dictionary<UIPanelType,BasePanel> ();
BasePanel panel = uiPanelScriptDict.tryGet<UIPanelType,BasePanel> (type);

扩展方法要放在一个静态类的静态方法中。

返回值等其他东西都照常语法,特殊的在于第一个参数,这里先用this再接要扩展的类,表名了扩展的这个TrtGet方法是在Dictionary里面的。

调用的时候,直接使用第一个参数类的对象调用方法,参数忽略第一个参数。