我正在尝试初始化对象列表(类型为Rep)。这是我用来初始化列表的代码:

        public static List<Rep> Reps = new List<Rep>(new Rep[6]);


现在,当我尝试为列表中的一个类中的字符串分配值时,如下所示:

 Repository.Reps[repnum].Main = new TextRange(richTextBox1.Document.ContentStart,
 richTextBox1.Document.ContentEnd).Text;


我是一个空引用异常。我究竟做错了什么?我找不到任何有关设置列表初始大小的Msdn文档。

最佳答案

我认为您可能会收到null引用异常,因为当您尝试设置Main属性的值时Repository.Reps [repnum]为null。您要做的是创建一个大小为6的代表数组,但是该数组中您对列表的所有引用均为空。尝试更新Rep对象并在其中设置其Main属性,如下所示:

Rep newRep = new Rep();
newRep.Main = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;

Repository.Reps[repnum] = newRep;


如果您打算首先让List中的所有值都为null,则使用List(int)构造函数并以这种方式创建List可能会更简单:

public static List<Rep> Reps = new List<Rep>(6);


但是,如果要在创建列表时使列表不包含空对象,则可以通过以下方式创建列表:

public static List<Rep> Reps = new List<Rep>()
{
    new Rep(),
    new Rep(),
    new Rep(),
    new Rep(),
    new Rep(),
    new Rep()
};

关于c# - 我在为类的List <T>分配初始大小时遇到​​麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2304416/

10-09 01:18
查看更多