【问题标题】:How does Enumerate work in MonoTouch?枚举在 MonoTouch 中是如何工作的?
【发布时间】:2023-03-22 23:45:01
【问题描述】:

在 MonoTouch 中,我需要处理 NSSet 中的每个对象。我使用 Enumerate 的尝试如下:

public override void ReturnResults ( BarcodePickerController picker, NSSet results )
{
    var n = results.Count;  // Debugging - value is 3
    results.Enumerate( delegate( NSObject obj, ref bool stop ) 
    {
        var foundCode = ( obj as BarcodeResult ); // Executed only once, not 3 times
        if ( foundCode != null )
        {
            controller.BarcodeScannedResult (foundCode);
        }
    });
// Etc
}

虽然在结果中使用三个对象调用该方法,但在委托中只处理了一个对象。我原以为委托会被执行 3 次,但我一定对它的工作原理有错误的想法。

找不到任何文档或示例。任何建议都非常感谢。

【问题讨论】:

    标签: xamarin.ios nsset enumerate


    【解决方案1】:

    您必须将ref 参数设置为false。这指示处理程序继续枚举:

    if ( foundCode != null )
    {
        controller.BarcodeScannedResult (foundCode);
        stop = false; // inside the null check
    }
    

    Here 是 Apple 文档中的 ObjC 等价物。

    【讨论】:

    • 不客气,很高兴我提供了帮助。请接受答案,以免其他 StackOverflow 用户将其视为未回答。
    【解决方案2】:

    或者你可以试试这个扩展方法让它变得更容易..

    public static class MyExtensions {
        public static IEnumerable<T> ItemsAs<T>(this NSSet set) where T : NSObject {
            List<T> res = new List<T>();
            set.Enumerate( delegate( NSObject obj, ref bool stop ) {
                T item = (T)( obj ); // Executed only once, not 3 times
                if ( item != null ) {
                    res.Add (item);
                    stop = false; // inside the null check
                }
             });
    
             return res;
        }
    }   
    

    然后你可以这样做:

    foreach(BarcodeResult foundCode in results.ItemsAs<BarcodeResult>()) {
        controller.BarcodeScannedResult (foundCode);
    }
    

    注意:请记住,这会创建另一个列表并将所有内容复制到其中,这样效率会降低。我这样做是因为匿名方法中不允许“yield return”,而且我能想到的使其成为没有副本的真正枚举器的替代方法是更多的代码。我处理的大多数套装都很小,所以这无关紧要,但如果你有一个大套装,这并不理想。

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2022-07-22
      • 2015-05-03
      • 1970-01-01
      相关资源
      最近更新 更多