我是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 :(得分: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。