我在BLL层中定义Post类。
中间有个静态方法
public static Post GetPostByID(int postID)
返回一个Post
但在网页中
使用 Post p=Post.GetPostByID(postid);
然后引用这个类的属性:例如p.Title,p.ForumID;
就会出现这个错误未将对象引用设置到对象的实例 直接用实例化函数 Post()的话,没有办法连接数据库,因为函数的定义

public Post(int id, DateTime addedDate, string addedBy, string addedByIP,
         int forumID, string forumTitle, int parentPostID, string title, string body, 
         bool approved, bool closed, int viewCount, int replyCount, string lastPostBy, DateTime lastPostDate)
      {
         this.ID = id;
         this.AddedDate = addedDate;
         this.AddedBy = addedBy;
         this.AddedByIP = addedByIP;
         this.ForumID = forumID;
         this.ForumTitle = forumTitle;
         this.ParentPostID = parentPostID;
         this.Title = title;
         this.Body = body;
         this.Approved = approved;
         this.Closed = closed;
         this.ViewCount = viewCount;
         this.ReplyCount = replyCount;
         this.LastPostBy = lastPostBy;
         this.LastPostDate = lastPostDate;
      }

请问怎么解决?

解决方案 »

  1.   

    证明此时的p是null
    你设断点看一下是怎么回事
      

  2.   

    这个异常就说明p此时此刻为null啊。BLL是你自己写的吗?是不是例如id不存在时就返回null?
      

  3.   

    这个是按照例子写的。
    public static Post GetPostByID(int postid)
            {
                Post post = null;
                string key = "Forums_Post_" + postid.ToString();
                if (BaseForum.Settings.EnableCaching && BizObject.Cache[key] != null)
                {
                    post = (Post)BizObject.Cache[key];
                }
                else
                {
                    post = GetPostFromPostDetails(SiteProvider.Forums.GetPostByID(postid));
                    BaseForum.CacheData(key, post);
                }
                return post;
            }
    例子里面可以正常运行。
    但我的不仅仅是这个函数,所有的返回POST的函数调用。
    都会出现这个问题。
      

  4.   

    post = (Post)BizObject.Cache[key]; 
    应该是这句的问题,强行转换不正确造成null值,这个只有自己调试才可以了解细节的,不然这样看不出来的
      

  5.   

    post = (Post)BizObject.Cache[key]; 这里有个强制类型转换。你把断点放这里看看 这行执行之后post对象是什么状态。是否为null。BizObject.Cache[key]这个方法的返回值是否确定能转换成Post?
      

  6.   

    值为Null,所以出错了,
    判断下如果是null就返回"",这样应该可以解决问题
      

  7.   

    Post p=Post.GetPostByID(postid); 
    if(p == null)
      return;
      

  8.   

    如你们所说果然是
    post = (Post)BizObject.Cache[key]; 
    这里出了问题。
    返回的是NUll;
      

  9.   

    找到解决方法!
    感谢各位帮助,现在贴出来:
    在插入缓存的参数里面。
    protected static void CacheData(string key, object data)
            {
                if (Settings.EnableCaching && data!= null)
                {
                    BizObject.Cache.Insert(key, data, null, DateTime.Now.AddSeconds(Settings.CacheDuration), TimeSpan.Zero);
                }
    }
    }其中Settings.CacheDuration没有赋值。
    赋值成60.就解决的了!
    呵呵。结贴喽~~
      

  10.   

    还是没有彻底解决。
    因为post = (Post)BizObject.Cache[key]; 
    bizobject不能强转换成post
    但post是继承bizobject。。搞不懂喽。。