简体   繁体   中英

Delegate in Xamarin.iOS

I have a problem in creating class for xamarin.ios delegate. In iOS we use protocols to implement the delegate but here I can not implement Interface as a delegate. Let me clear this concept. I have an interface in one file like:

public interface SendBackDelegate
{
     void sendBackData();
}

public class SelectList
{

}

In other file I have main class like this:

public class ShowList: SendBackDelegate
{
    public ShowList()
    {
        SelectList obj = new SelectList();
        obj.delegate = this;
    }
    void sendBackData()
    {
        Console.WriteLine("Send Back DATA");
    }
}

Now Can you please tell me how this interface be implemented in SelectList class?

Thanks

you can use Interface like protocol, only you have to make reference object of interfaces it can own the class object which already implemented the Interface methods. it will be clear with your example as well.

public interface SendBackDelegate
{
     void sendBackData();
}

public class SelectList
{
     ShowList  showListObj = new ShowList();
     SendBackDelegate delegate = showListObj;
     delegate.sendBackData();
     //this will call the method sendBackData()  of class ShowList.    
}    

public class ShowList: SendBackDelegate
{
    public ShowList()
    {
        SelectList obj = new SelectList();
        obj.delegate = this;
    }
    void sendBackData()
    {
        Console.WriteLine("Send Back DATA");
    }
}

Please let me know if you still have questions.

I am not using delegates anymore on Xamarin.iOS. I prefer to use actions though.

class MainClass
{
    public static void Main (string[] args)
    {
        var x = new ShowList ();
    }
}

public interface SendBackDelegate
{
    void sendBackData ();
}

public class ShowList : SendBackDelegate
{
    public ShowList ()
    {
        SelectList obj = new SelectList (sendBackData);
    }

    public void sendBackData ()
    {
        Console.WriteLine ("Send Back DATA");
    }
}

public class SelectList
{
    Action _callback;

    public SelectList (Action callback)
    {
        _callback = callback;
        Ticker ();
    }

    private void Ticker ()
    {
        _callback ();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM