带参数的C#传递动作

时间:2017-02-20 14:08:39

标签: c# callback delegates action ilspy

今天我正在寻找一些使用ilspy的项目我不明白如何使用这样的动作,在一个类中这个方法被称为

    public void Login(Action success, Action<bool> failure)
    {
        if (!FB.IsInitialized)
        {
            Debug.Log("[FB] Not yet initialized. Will init again!");
            FB.Init(new InitDelegate(this.OnInitComplete), null, null);
            return;
        }
        new LoginWithReadPermissions(this.READ_PERMISSIONS, delegate
        {
            ServiceLocator.GetDB().SetBool("facebookBound", true, false);
            this.OnLoginCompleted(success, failure);
        }, delegate
        {
            failure(false);
        });
    }

这是上面方法调用的另一个类

    public class LoginWithReadPermissions
{
    private readonly Action _failureCallback;

    private readonly Action _successCallback;

    public LoginWithReadPermissions(string[] scope, Action success, Action failure)
    {
        this._successCallback = success;
        this._failureCallback = failure;
        FB.LogInWithReadPermissions(scope, new FacebookDelegate<ILoginResult>(this.AuthCallback));
    }

    private void AuthCallback(ILoginResult result)
    {
        if (result.Error == null && FB.IsLoggedIn)
        {
            this._successCallback();
        }
        else
        {
            this._failureCallback();
        }
    }
}

有人可以解释那里发生了什么我从未遇到过这种动作用法。谢谢你的回复。

1 个答案:

答案 0 :(得分:0)

public void Login(Action success, Action<bool> failure)
{
    if (!FB.IsInitialized)
    {
        Debug.Log("[FB] Not yet initialized. Will init again!");
        FB.Init(new InitDelegate(this.OnInitComplete), null, null);
        return;
    }
    new LoginWithReadPermissions(this.READ_PERMISSIONS, delegate
    {
        ServiceLocator.GetDB().SetBool("facebookBound", true, false);
        this.OnLoginCompleted(success, failure);
    }, delegate
    {
        failure(false);
    });
}

上面的代码只是简写:

public void Login(Action success, Action<bool> failure)
    {
        Action successAction = () =>
        {
            ServiceLocator.GetDB().SetBool("facebookBound", true, false);
            this.OnLoginCompleted(success, failure);
        };

        Action failureAction = () =>
        {
            failure(false);
        };

        if (!FB.IsInitialized)
        {
            Debug.Log("[FB] Not yet initialized. Will init again!");
            FB.Init(new InitDelegate(this.OnInitComplete), null, null);
            return;
        }
        new LoginWithReadPermissions(this.READ_PERMISSIONS, successAction, failureAction);
    }