如何从对象内部函数调用类函数

时间:2017-06-02 13:11:44

标签: c# unity3d delegates

我是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; }

}

1 个答案:

答案 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

相关问题