For the list of these sequential tables, we can use the for instead of foreach when we solve them. But for non-sequential tables, such as dictionary or set, we can extend the methods Foreach,foreachkey and Foreachvalue instead of the original foreach.
For extension methods, refer to: https://msdn.microsoft.com/zh-cn/library/bb383977.aspx
Static Class dictionaryex{///<summary>Provides a way to traverse all items///</summary>PublicStaticvoid Foreach<tkey, Tvalue> (This dictionary<tkey, tvalue> dic, Action<tkey, tvalue> Action,int maxCount =1000) {if (action = =NullReturnvar enumerator = dic. GetEnumerator ();int i =0;while (enumerator. MoveNext () && i++ < MaxCount) {action (enumerator. Current.key, Enumerator. Current.value); } }///<summary>Provides a way to traverse all key values///</summary>PublicStaticvoid Foreachkey<tkey, Tvalue> (This dictionary<tkey, tvalue> DiC, action<tkey> Action,int maxCount =1000) {if (action = =NullReturnvar enumerator = dic. GetEnumerator ();int i =0;while (enumerator. MoveNext () && i++ < MaxCount) {action (enumerator. Current.key); } }///<summary>///provides a way to traverse all value values ///</summary> public static void Foreachvalue<tkey, Tvalue> ( this Dictionary<tkey, tvalue> dic, action<tvalue> Action, int maxCount = 1000" {if (action = = null" return; var enumerator = dic. GetEnumerator (); int i = 0; while (enumerator. MoveNext () && i++ < MaxCount) {action (enumerator. Current.value); } }}
When called, we can use lambda expressions to simplify code, such as:
prote CTED dictionary<int, releaseonceskillbunchlistshell> m_SkillBunchList = new dictionary<int, releaseonceskillbunchlistshell> (); //a skill list /// //////////public void update ( Float deltatime) {//update skill list m_skillbunchlist.foreachvalue ((value. Update (deltatime); }); }
This thought this solves the problem, the result opens the profiler to look, the mother egg, unexpectedly also has the GC, carefully contrasts discovers, originally is the lambda expression question. No way, after the lambda expression was taken apart, the following is done.
protected float m_deltaTime; public void Update(float deltaTime) { m_deltaTime = deltaTime; m_SkillBunchList.ForeachValue(OnUpdateSkillBunch); } public void OnUpdateSkillBunch(ReleaseOnceSkillBunchListShell shell) { shell.Update(m_deltaTime); }
The place of the Deltatime is, the original scope of the inside, need to be placed in a higher level of the scope, otherwise bad access.
So, be careful, lambda expressions also produce gc!
Use extension method in unity to resolve GC caused by foreach