我有一个c#List的问题,在向Managepagesid列表中添加新对象时,我不确定错过了哪一点!
public class Clients
{
[BsonId]
public string Id { get; set; } //Object ID managed by MongoDb
public string Name { get; set; } //Client Name
public string Phone { get; set; } //Client Phone
public string Email { get; set; } //Client E-mail
public string Username { get; set; } //Client Username
public DateTime LastModified { get; set; } //Client Last Login
public string FB_User_Id { get; set; } //Client FB User ID
public AccessToken UserAccessToken { get; set; } //AccessToken which is stored while user is logged in.
public List<ManagePages> Manage_Pages_id { get; set; } //The pages maintained by the specific client
}
我正在尝试访问在ManagePage_id列表中添加一个新项目,但它会抛出一些null异常..帮助!
Clients client = new Clients();
client.FB_User_Id = FBData.id;
client.Name = FBData.name;
client.Email = FBData.email;
client.Username = FBData.username;
for (int index = 0; index < FBData.accounts["data"].Count; index++)
{
ManagePages pagedetails = new ManagePages()
{
page_id = FBData.accounts["data"][index].id,
page_name = FBData.accounts["data"][index].name,
ManagePages_AccessTokens = new AccessToken()
{
AccessToken_accessToken = FBData.accounts["data"][index].access_token,
AccessToken_expiryDate = DateTime.Now
},
ManagePages_category = FBData.accounts["data"][index].category
};
var category = pagedetails.ManagePages_category;
client.Manage_Pages_id.Add(pagedetails);
}
Stack Trace添加了!
异常&gt; System.NullReferenceExceptionObject引用未设置为对象的实例。在G:\ Development \ Vega_MongoDB \ Vega_MongoDB \ FBDataAccess \ ClientFBRepository.cs中的Vega_MongoDB.FBDataAccess.ClientFBRepository.ClientsData(String accessToken):第48行 在G:\ Development \ Vega_MongoDB \ Vega_MongoDB \ Models \ Clients \ ClientRepository.cs中的Vega_MongoDB.Models.ClientRepository..ctor(字符串连接):第47行 在G:\ Development \ Vega_MongoDB \ Vega_MongoDB \ Models \ Clients \ ClientRepository.cs中的Vega_MongoDB.Models.ClientRepository..ctor():第23行 在Vega_MongoDB.Controllers.ClientsController..cctor()中的g:\ Development \ Vega_MongoDB \ Vega_MongoDB \ Controllers \ ClientsController.cs:第18行
我检查了pagedetails对象,它包含所有数据..
由于
毗
答案 0 :(得分:2)
您应该在添加项目之前创建列表实例:
client.Manage_Pages_id = new List<ManagePages>();
for (int index = 0; index < FBData.accounts["data"].Count; index++)
{
ManagePages pagedetails = new ManagePages()
{
page_id = FBData.accounts["data"][index].id,
page_name = FBData.accounts["data"][index].name,
ManagePages_AccessTokens = new AccessToken()
{
AccessToken_accessToken = FBData.accounts["data"][index].access_token,
AccessToken_expiryDate = DateTime.Now
},
ManagePages_category = FBData.accounts["data"][index].category
};
var category = pagedetails.ManagePages_category;
client.Manage_Pages_id.Add(pagedetails);
}
答案 1 :(得分:1)
尝试将此添加到您的班级:
public Clients()
{
this.Manage_Pages_id = new List<ManagePages>();
}
答案 2 :(得分:1)
您需要在添加任何内容之前初始化列表。您可以在Clients
类的构造函数或调用代码中执行此操作(如Artem建议的那样)。
public class Clients
{
//properties
public Clients()
{
Manage_Pages_id = new List<ManagePages>();
}
}