尝试存储在变量字符串中时的NullReference

时间:2014-05-20 14:20:08

标签: c# vb.net nullreferenceexception

我的解决方案中有两个项目:HomeworkCalendar(VB.net Windows Forms Application)和HWLib(C#.dll类库)。在库中的CurrentUser类中,我将变量定义为HWLib.User currentUser。这来自HWLib中的User类:

namespace HWLib
{
    public class User
    {
        /// <summary>
        /// The Name of the User
        /// </summary>
        public String name = null;
        /// <summary>
        /// The Age of the User
        /// </summary>
        public int age = 0;
        /// <summary>
        /// The School Type of the User
        /// </summary>
        public String school = null;
        /// <summary>
        /// The Amount of Classes the User
        /// </summary>
        public int classesCount = 0;
        /// <summary>
        /// The String Array that holds all the classes
        /// </summary>
        public string[] classes;
    }
 }

这与CurrentUser类

中的情况相同
public class CurrentUser
{
    /// <summary>
    /// The current User using the program
    /// </summary>
    public static HWLib.User currentUser;
}

所以我试图将用户信息存储到这个变量中,但这是我得到NullReferenceException

的地方
Try
    If intClasses <= 11 Then
        CurrentUser.currentUser.name = txtName.Text
        CurrentUser.currentUser.classesCount = intClasses
        CurrentUser.currentUser.school = cboSchool.SelectedItem
        CurrentUser.currentUser.age = Convert.ToInt32(cboAge.SelectedItem)
    End if
Catch exx As NullReferenceException
   'It does catch! This is the issue! Why does it catch here and how do I fix it?
    File.Delete(Base.filePath)
    MsgBox(exx.ToString())
End Try

1 个答案:

答案 0 :(得分:2)

好吧,为了让它运行,您需要初始化currentUser

public class CurrentUser
{
    /// <summary>
    /// The current User using the program
    /// </summary>
    public static HWLib.User currentUser = new HWLib.User() ;
}

但:

  1. 为什么你有一个只有静态属性的非静态类?只需CurrentUser静态
  2. 即可
  3. 使用属性(使用getter / setter)代替字段是一种更好的做法。这允许您在不破坏客户端代码的情况下向get / set添加逻辑。