ABAddressBook mybook = new ABAddressBook(); ABPerson[] allPeople = mybook.GetPeople(); foreach(ABPerson thisPerson in allPeople){ if(thisPerson.GetPhones() != null) ABMultiValue<string> myMultiPhone = thisPerson.GetPhones(); } }
在try-catch中包装代码在一定程度上是可行的,但并不总是如此。有时它会得到所有的电话号码没有问题,而其他时候,它停止了随机获得电话号码和尝试捕捉投诉“错误发生获取电话号码。句柄不能为空。 参数名称:handle“
不要这样做——特别是,不要像那样连续调用ABPerson.GetPhones()。这个 ABMultiView<string> 包装本机资源(这就是为什么 ABMultiValue<T> IDisposable
ABMultiView<string>
更好的方法是:
var mybook = new ABAddressBook(); foreach (var person in mybook.GetPeople()) { using (var phones = person.GetPhones()) { if (phones != null) { // do something with phones... } } }
这将确保资源被清理,而不需要依赖GC在以后清理它们。
ABMultiValue<string> 实例),GC将其中几个标记为垃圾,然后终结器进入并运行析构函数…它调用本机代码来清理资源…但是本机库在这里可能不是线程安全的。只是一个猜测。
ABMultiValue<string>