C# 试图存储在变量';s弦

C# 试图存储在变量';s弦,c#,vb.net,nullreferenceexception,C#,Vb.net,Nullreferenceexception,我的解决方案中有两个项目:HomeworkCalendar(VB.net Windows窗体应用程序)和HWLib(C#.dll类库)。在库中的CurrentUser类中,我有一个变量定义为HWLib.User CurrentUser。这来自HWLib中的用户类: namespace HWLib { public class User { /// <summary> /// The Name of the User //

我的解决方案中有两个项目:HomeworkCalendar(VB.net Windows窗体应用程序)和HWLib(C#.dll类库)。在库中的CurrentUser类中,我有一个变量定义为
HWLib.User CurrentUser
。这来自HWLib中的用户类:

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 = new HWLib.User() ;
}
公共类CurrentUser
{
/// 
///使用该程序的当前用户
/// 
public static HWLib.User currentUser=new HWLib.User();
}
但是:

  • 为什么只有一个静态属性的非静态类?只需将当前用户设置为静态
  • 更好的做法是使用属性(带有getter/setter)而不是字段。这允许您在不破坏客户机代码的情况下向get/set添加逻辑

  • currentUser
    未初始化。哪一行引发异常?使用调试器!!在该行上放置断点,然后运行程序。当它到达该断点时,将鼠标悬停在各种变量上。它会告诉你哪一个是空的;10个左右,就在那边===>下面谢谢!我犯了一个愚蠢的错误。我真的应该知道这是需要的。
    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
    
    public class CurrentUser
    {
        /// <summary>
        /// The current User using the program
        /// </summary>
        public static HWLib.User currentUser = new HWLib.User() ;
    }