试图在变量's字符串中存储null引用

本文关键字:字符串 存储 null 引用 变量 | 更新日期: 2023-09-27 18:04:09

我有两个项目在我的解决方案:HomeworkCalendar (VB.net Windows窗体应用程序)和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

试图在变量's字符串中存储null引用

要让它运行你需要初始化currentUser:

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

但:

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