2017-06-02 39 views
0

調用類的功能,我的Java開發新的C#的概念。我想從匿名內部函數中調用類函數(用java語言不知道它在C#中調用的是什麼)。如何從物體內部函數

public void test() 
{ 
    this.apiManager.send (RequestMethod.GET, "/admin", "", callback1); 
} 


ApiCallback callback = new ApiCallback() { 
    onSuccess = (string response, long responseCode) => { 
     Debug.Log (response); 
     Debug.Log (responseCode + ""); 
     test(); 
    }, 
    onError = (string exception) => { 
     Debug.Log (exception); 
    } 
}; 

所以就這樣做我收到以下錯誤

A field initializer cannot reference the nonstatic field, method, or property "test()"

這裏是ApiCallback

public class ApiCallback 
{ 
    public delegate void SuccessCreater (string response, long responseCode); 

public delegate void ErrorCreater (string error); 

public SuccessCreater onSuccess { get; set; } 

public ErrorCreater onError { get; set; } 

} 
+0

不同的範圍,如果你想做到這一點,你必須分配'static'您的測試方法。 –

+0

這將有助於看到'test'聲明和_where_實例化'callback'。但我想這會表明克里斯托夫是對的。 –

+0

聲明的測試方法爲公共靜態無效測試() – Curious

回答

2

的實現,則必須實例化代碼移動到你的構造:

public YourClassNameHere() 
{ 
    callback = new ApiCallback() 
    { 
     onSuccess = (string response, long responseCode) => { 
      Debug.Log(response); 
      Debug.Log(responseCode + ""); 
      test(); 
     }, 
     onError = (string exception) => { 
      Debug.Log(exception); 
     } 
    }; 
} 

替代地使用(從場切換到屬性):

ApiCallback callback => new ApiCallback() 
    { 
     onSuccess = (string response, long responseCode) => { 
      Debug.Log(response); 
      Debug.Log(responseCode + ""); 
      test(); 
     }, 
     onError = (string exception) => { 
      Debug.Log(exception); 
     } 
    }; 

詳情請參閱A field initializer cannot reference the nonstatic field, method, or property