【问题标题】:Callbacks in C# androidC# android 中的回调
【发布时间】:2013-12-27 20:14:46
【问题描述】:

我已经在 Handler(在 java 中)上实现了回调。我需要在 c#(Xamarin) 上实现相同的功能。但截至目前,我无法找到如何在 C# 中执行此操作的任何解决方案。我是 c# 新手,因此知识很少。

这里是java代码:-

private Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg)
    {
      if (msg.what == MSG_SURFACE_CREATED)
      {
        contentWidth = 0;
        contentHeight = 0;
        requestLayout();
        return true;
      } 
      else
      {
        Log.w("Unknown msg.what: " + msg.what);
      }
      return false;
    }
  });

有什么想法可以在 C# 中实现吗?

【问题讨论】:

    标签: c# java android


    【解决方案1】:

    IN Xamarin 您仍将使用由关键字“delegate”定义的这种“内联”方法。 这是因为,回调是函数指针,c# 支持这一点,java 不支持,xamarin 也不支持,但是尝试生成一个桥。 此处描述了 xamarin 中的代表:

    http://docs.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events/

    【讨论】:

    • 感谢您的关注。如果您能给我一个与我在 java 中的代码相关的示例,将会很有帮助。
    • 这里有很多:stackoverflow.com/questions/2983250/… 这种方法称为“observer-observable-pattern”。在 xamarin studion 中可以下载“常用示例”。他们也涵盖了这个主题。
    【解决方案2】:

    事件是要走的路(使用委托)。下面是一些示例代码:

    class CallingClass
    {
        private SurfaceCreatingClass m_surfacecreatingclass;
    
        public CallingClass()
        {
            m_surfacecreatingclass = new SurfaceCreatingClass();
            m_surfacecreatingclass.SurfaceCreatedHandler += OnFinished;
            m_surfacecreatingclass.CreateSurface();
        }
    
        void OnFinished(int iMessageWhat)
        {
            if (iMessageWhat == SurfaceCreatingClass.MSG_SURFACE_CREATED)
            {
                contentWidth = 0;
                contentHeight = 0;
                RequestLayout();
            }
            else
            {
                Log.w("Unknown msg.what: " + iMessageWhat);
            }
        }
    }
    
    class SurfaceCreatingClass
    {
        public delegate void SurfaceCreatedDelegate(int iWhat);
        public event SurfaceCreatedDelegate SurfaceCreatedHandler;
        public const int MSG_SURFACE_CREATED = 1;
    
        public void CreateSurface()
        {
            /////////////////////////////
            // Surface creation code here
            // ...
            /////////////////////////////
    
            if (SurfaceCreatedHandler != null)
                SurfaceCreatedHandler(MSG_SURFACE_CREATED);
        }
    }
    

    【讨论】:

    • 感谢您的关注,但我很抱歉,因为我对 c# 很陌生。您能指导我如何处理问题中的代码吗?
    • 我已经修改了代码,使其看起来更像您的原始示例,尽管它与以前基本相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多