您尚未将数组初始化为任何大小。并且您正在尝试访问该元素
info.Subcategories[0] = 1;
这就是为什么你得到例外。
在使用之前或在构造函数中将它们初始化为一定大小。
public void TestDecreaseTutorArea()
{
HelpWith info = new HelpWith();
info.SubCategories = new int[10]; //here
info.Subcategories[0] = 1;
info.UserId = 14;
TutorService tutorService = new TutorService();
tutorService.DecreaseTutorArea(info);
}
或者在类构造函数中:
public class HelpWith
{
public int UserId { get; set; }
public int[] Categories { get; set; }
public int[] Subcategories { get; set; }
//constructor
public HelpWith()
{
this(10,10);
}
public HelpWith(int CategorySize, int SubCategorySize)
{
Categories = new int[CategorySize]; //some size
SubCategories = new int[SubCategorySize];
}
}
如果您事先不知道数组的大小,请使用List<int>
,但请记住在构造函数中对其进行初始化,例如:
public class HelpWith
{
public int UserId { get; set; }
public List<int> Categories { get; set; }
public List<int> Subcategories { get; set; }
//constructor
public HelpWith()
{
Categories = new List<int>();
Subcategories = new List<int>();
}
}
然后使用它:
[TestMethod]
public void TestDecreaseTutorArea()
{
HelpWith info = new HelpWith();
info.Subcategories.Add(1);
info.UserId = 14;
TutorService tutorService = new TutorService();
tutorService.DecreaseTutorArea(info);
}