C# 在MVC2中为列表添加值时,对象引用未设置为对象执行的实例

C# 在MVC2中为列表添加值时,对象引用未设置为对象执行的实例,c#,asp.net-mvc-2,automatic-properties,C#,Asp.net Mvc 2,Automatic Properties,对象引用未设置为引发的对象异常的实例..(用户代码未处理Null referenceException) 型号: public class AboutMod { private List<int> divWidthList = new List<int>(); public List<int> DivWidthList { get; set; } } public类AboutMod { 私有列表divWidthList=新列表(); 公共列表

对象引用未设置为引发的对象异常的实例..(用户代码未处理Null referenceException)

型号:

public class AboutMod
{
    private List<int> divWidthList = new List<int>();
    public List<int> DivWidthList { get; set; }
}
public类AboutMod
{
私有列表divWidthList=新列表();
公共列表DivWidthList{get;set;}
}
控制页:

 public ActionResult About()
        {
            AboutMod Obj = new AboutMod();//model class name 
            for (int i = 20; i <= 100; i += 20)
            {
                Obj.DivWidthList.Add(10);//Run time Exception occurs here 
            }
                return View();
        }
public ActionResult About()
{
AboutMod Obj=new AboutMod();//模型类名

对于(int i=20;i您的私有字段
divWidthList
和公共属性
divWidthList
之间绝对没有关系。公共属性从未初始化。您可以在类的构造函数中初始化它,例如:

public class AboutMod
{
    public AboutMod
    {
        DivWidthList = new List<int>();
    }
    public List<int> DivWidthList { get; set; }
}
public类AboutMod
{
公共交通工具
{
DivWidthList=新列表();
}
公共列表DivWidthList{get;set;}
}
或者不使用自动属性:

public class AboutMod
{
    private List<int> divWidthList = new List<int>();
    public List<int> DivWidthList 
    {
        get
        {
            return divWidthList;
        }
        set
        {
            divWidthList = value;
        }
    }
}
public类AboutMod
{
私有列表divWidthList=新列表();
公开名单
{
得到
{
返回列表;
}
设置
{
divWidthList=值;
}
}
}

在尝试使用之前,先初始化
Obj.DivWidthList

    AboutMod Obj = new AboutMod();//model class name 

    Obj.DivWidthList = new List<int>();

    for (int i = 20; i <= 100; i += 20)
    {            
        Obj.DivWidthList.Add(10);//Run time Exception occurs here 
    }
AboutMod Obj=new AboutMod();//模型类名
Obj.DivWidthList=新列表();
对于(int i=20;i