错误:无法执行运行时绑定(在facebook配置文件中未设置location/hometown /任何设置时)

Nik*_*pta 9 c# facebook facebook-c#-sdk

我正面临一个错误

无法对空引用执行运行时绑定

描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.

异常详细信息:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法对空引用执行运行时绑定

来源错误:

第27行:lblBirthday.Text =(myInfo.birthday == null?string.Empty:DateTime.Parse(myInfo.birthday).ToString("dd-MMM-yy")); 第28行:lblHometown.Text =(myInfo.hometown.name == null?string.Empty:myInfo.hometown.name); 第29行:lblLocation.Text =(myInfo.location.name == null?string.Empty:myInfo.location.name); 第30行:pnlHello.Visible = true; 第31行:}

这是我的代码:

var fb = new FacebookWebClient();
    dynamic myInfo = fb.Get("me");
    lblName.Text = myInfo.name;
    imgProfile.ImageUrl = "https://graph.facebook.com/" + myInfo.id + "/picture";
    lblBirthday.Text = (myInfo.birthday == null ? string.Empty : DateTime.Parse(myInfo.birthday).ToString("dd-MMM-yy"));
    lblHometown.Text = (myInfo.hometown.name == null ? string.Empty : myInfo.hometown.name);
    lblLocation.Text = (myInfo.location.name == null ? string.Empty : myInfo.location.name);
    pnlHello.Visible = true;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 14

首先检查是否为myInfo.locationnull:

lblLocation.Text = myInfo.location == null ? "" : myInfo.location.name ?? "";
Run Code Online (Sandbox Code Playgroud)

(同样对于类似的成员.)

无可否认,这有点痛苦,但基本上你需要考虑任何可能为空的东西,以确保你不要试图取消引用它.