当循环遍历Xamarin.Forms android项目中的联系人时,我得到以下错误
“'System.Collections.Generic.IEnumerable1[Xamarin.Contacts.Contact]' cannot be used for return type 'System.Linq.IQueryable1Xamarin.Contacts.Contact'”类型的表达
有趣的是,我在bugzilla中发现了同样的错误,但是没有提到分辨率。
谁能帮我解决这个错误吗?
以下是方法:
public async Task<IEnumerable<MobileUserContact>> All()
{
if (_contacts != null) return _contacts;
var contacts = new List<MobileUserContact>();
try
{
if (!await _book.RequestPermission())
{
Console.WriteLine("Permission denied");
return;
}
foreach (Contact contact in _book.OrderBy(c => c.LastName))
{
Console.WriteLine("{0} {1}", contact.FirstName, contact.LastName);
contacts.Add(new MobileUserContact(contact.FirstName, contact.LastName, ""));
}
return contacts;
}
catch (Exception ex)
{
throw;
}
}它使用的是Xamarin.Mobile 0.7.1.0版本的dll
我已经启用了Read_Contacts权限
发布于 2017-03-07 10:38:04
如果这是一个Xamarin.Mobile包问题,也许您可以提交一个问题这里。在这里,我不能修复这个错误,但只能提出两个解决方案,不使用这个Xamarin.Mobile包来获取联系人。
当您编写像这个MobileUserContact这样的代码时,您的var contacts = new List<MobileUserContact>();应该是一个类,但是在这里使用它就像一个方法:contacts.Add(new MobileUserContact(contact.FirstName, contact.LastName, ""));。
无论如何,我创建了一个试着重现问题的演示程序,下面的代码在我身边运行得很好:
public List<MobileUserContact> contacts;
public async Task<IEnumerable<MobileUserContact>> All()
{
contacts = new List<MobileUserContact>();
try
{
if (!await CrossContacts.Current.RequestPermission())
{
return null;
}
foreach (var contact in CrossContacts.Current.Contacts.ToList())
{
contacts.Add(new MobileUserContact
{
FirstName = contact.FirstName,
LastName = contact.LastName
});
}
return contacts;
}
catch (Exception ex)
{
throw;
}
}MobileUserContact类在这里很简单:
public class MobileUserContact
{
public string FirstName { get; set; }
public string LastName { get; set; }
}除了READ_CONTACTS权限外,我们还需要注意,这个插件只针对23+,并针对23+为Android平台编译。
使用此包的优点是所有代码都可以放在PCL中,但是这个包目前在Alpha中是,目前还不完全支持。
DependencyService并使用Android的本地API来获取联系人。例如,本地Android项目中的代码可以如下所示:
var cursor = Android.App.Application.Context.ContentResolver.Query(Phone.ContentUri, null, null, null, null);
contacts = new List<MobileUserContact>();
while (cursor.MoveToNext())
{
contacts.Add(new MobileUserContact
{
FirstName = cursor.GetString(cursor.GetColumnIndex(Phone.InterfaceConsts.DisplayName)),
Num = cursor.GetString(cursor.GetColumnIndex(Phone.Number))
});
}https://stackoverflow.com/questions/42632158
复制相似问题