对象引用未设置为对象的实例

本文关键字:实例 对象 设置 对象引用 | 更新日期: 2023-09-27 18:00:33

我已经搜索了很多线程和网站来寻找这个问题。到目前为止,我还没有发现这个代码有任何错误。

"坏"代码是这样的:请求。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);

对象引用未设置为对象的实例

此代码段可能引发NullReferenceException的唯一方法是,如果request.Retrieve返回null,而如果任一参数为null,则request.AddComment引发异常。

解决方案是测试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...
}

空检查被引用的对象。应明确检查视频请求。下面的代码执行视频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.
    }