2011-06-28 175 views
0

我已经通过很多线程和网站搜索了这个问题。到目前为止,我还没有发现这个代码有什么问题。未将对象引用设置为对象的实例

“坏”的代码是这样的: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); 
+5

请添加堆栈跟踪或至少是有问题的行 –

+0

您可以发布堆栈跟踪吗? –

+2

在这一行中最可疑的是'Video v = request.Retrieve

回答

3

这段代码有可能抛出的唯一方式NullReferenceException是,如果request.Retrieve返回nullrequest.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... 
} 
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. 
    } 
+0

'new' _cannot_ return'null'。测试'request'是不必要的。 –

+0

我的不好,视频应该检查。我已经更新了代码,Thx指出了这一点。 –

+0

谢谢,现在我知道v返回null:/现在我所需要做的就是试着让它返回其他东西。 – George

相关问题