我对以下代码有问题。它使用 Facebook c# SDK。问题是我正在提取并打印我所有朋友工作历史的列表。但是,当这些数据不可用时,我认为它会导致 NullReferenceException。我在网上查看了一堆解决方案,但没有找到一个似乎有效的解决方案。任何帮助,将不胜感激。
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = "...";
var client = new FacebookClient(accessToken);
dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });
foreach (dynamic friend in myInfo)
{
foreach (dynamic work in myInfo.work) // <---- here
{
Response.Write("Employer: " + work.employer.name + "<br/> Position:" + work.position.name + "<br/><br/>");
}
}
}
}
我已经包含了建议的编辑,但现在出现了一个不同的错误:
namespace WebApplication1.Site
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = "xxx";
var client = new FacebookClient(accessToken);
dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });
foreach (dynamic friend in myInfo)
{
**foreach (dynamic work in friend.work ?? new[] { new { employer = new { name = string.Empty }, position = new { name = string.Empty } } })**
{
Response.Write("Employer: " + myInfo.work.employer.name);
}
}
}
}
}
“System.Collections.Generic.KeyValuePair”在第 21 行不包含“work”的定义