我搜索了许多寻找此问题的主题和网站。到目前为止,我还没有发现此代码有任何问题。
“坏”代码是这样的:request.AddComment(v,c);
另外,我不知道堆栈跟踪是什么。
提前感谢您的帮助。
这是我的代码:
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a =
new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);
答案 0 :(得分:3)
此代码段可能抛出NullReferenceException
的唯一方法是request.Retrieve
返回null
而request.AddComment
如果任一参数为null
则抛出异常。
解决方案是测试v
:
Video v = request.Retrieve<Video>(uri);
if(v != null)
{
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);
}
else
{
// something went wrong when getting the video...
}
答案 1 :(得分:0)
Null检查被引用的对象。应该检查视频请求。下面的代码会进行视频空检查。
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a = new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
if (v!= null)
{
request.AddComment(v, c);
}
else
{
//Handle the null, try to get the video again, report to user, etc.
}