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里面的。
调用的时候,直接使用第一个参数类的对象调用方法,参数忽略第一个参数。