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

阿布舍克·帕蒂达尔

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

}
微博

您必须将实例化代码移至构造函数:

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);
        }
    };

有关更多详细信息请参阅字段初始值设定项不能引用非静态字段、方法或属性

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章