2013-06-23 27 views
1

我試圖加載不同的函數而不使用太多的if語句(C#)。我嘗試使用列表,但是對於Unity,使用Action引發異常。 我發現這裏的C#一個很好的解決方案:將函數存儲在Unity3D的列表或數組中

var methods = new Dictionary<string, Action>() 
      { 
       {"method1",() => method1() }, 
       {"method2",() => method2() } 
      }; 

methods["method2"](); 

同樣在這裏與Action

問題我進口

using System.Collections.Generic; 

我怎麼錯過?

回答

1

System.Collections.GenericDictionary之外,還需要爲Action導入System

using System;添加到文件頂部。

通常,查看MSDN上的類型以查看其完整名稱空間。在這種情況下,Action delegate的MSDN頁面指示其名稱空間是「System」。因此,您必須在代碼頂部添加using System;指令,或者在代碼中包含完整的名稱空間。因此,舉例來說,如果您有以下指令,則可以使用using指令重寫上述代碼:

var methods = new System.Collections.Generic.Dictionary<string, System.Action>() 
     { 
      {"method1",() => method1() }, 
      {"method2",() => method2() } 
     }; 

methods["method2"]();