检查下面的代码。我想将列表值设置为StorageFileDisplay
类的MainFolderDisplay
类。所以我想在控制器中做的是-
var mainFolder
初始化MainFolderDisplay
类,然后尝试访问名为SubFolderDisplay
的列表内的StorageFileDisplay
,然后尝试为该StorageFileDisplay
列表设置新值。但是当前代码的问题在于它无法访问mainFolder.SubFolderDisplay.StorageFileDisplay
并引发异常-
实例未设置为对象的实例
任何人都可以告诉我如何从称为SubFolderDisplay.StorageFileDisplay.StorageFileDisplay
的主要指标中为MainFolderDisplay
列表增加价值?预先感谢
控制器:
var mainFolder = new MainFolderDisplay();
mainFolder.SubFolderDisplay.StorageFileDisplay.Add(new StorageFileDisplay
{
AwsUniqueFileName = "foo",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "foo",
UserId = 0,
});
型号:
using Test.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Test.ViewModels
{
public class MainFolderDisplay
{
public int MainFolderId { get; set; }
public string MainFolderName { get; set; }
public int UserId { get; set; }
public List<StorageFileDisplay> StorageFileDisplay { get; set; }
public List<SubFolderDisplay> SubFolderDisplay { get; set; }
}
public class SubFolderDisplay
{
public int SubFolderId { get; set; }
public string SubFolderName { get; set; }
public int MainFolderId { get; set; }
public List<StorageFileDisplay> StorageFileDisplay { get; set; }
}
public class StorageFileDisplay
{
public int FileId { get; set; }
public string AwsUniqueFileName { get; set; }
public string UserDisplayFileName { get; set; }
public int UserId { get; set; }
public int FolderType { get; set; }
public int RelatedFolderId { get; set; }
}
}
答案 0 :(得分:1)
您还必须实例化所有嵌套属性,默认情况下它们为null。试试这个:
var mainFolder = new MainFolderDisplay
{
SubFolderDisplay = new List<SubFolderDisplay>
{
new SubFolderDisplay
{
StorageFileDisplay = new List<StorageFileDisplay>
{
new StorageFileDisplay
{
AwsUniqueFileName = "foo",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "foo",
UserId = 0,
}
}
}
}
};
答案 1 :(得分:1)
实例未设置为对象的实例。
这显然是您在尝试对实际上为空的内容执行操作。
这意味着您在StorageFileDisplay
对象中的SubFolderDisplay
和MainFolderDisplay
列表为空。因此,首先您必须初始化这些列表。您可以在MainFolderDisplay
类中进行以下操作:
public class MainFolderDisplay
{
public MainFolderDisplay()
{
StorageFileDisplay = new List<StorageFileDisplay>();
SubFolderDisplay = new List<SubFolderDisplay>();
}
public int MainFolderId { get; set; }
public string MainFolderName { get; set; }
public int UserId { get; set; }
public List<StorageFileDisplay> StorageFileDisplay { get; set; }
public List<SubFolderDisplay> SubFolderDisplay { get; set; }
}
答案 2 :(得分:0)
我认为SubFolderDisplay或StorageFileDisplay列表未实例化。确保在添加
之前new List<SubFolderDisplay>()
new List<StorageFileDisplay>()