索引器允许对类或结构的实例进行索引 阵列。索引器类似于属性,除了它们的访问器 参数。
我有这样的代码
class StudentMemento
{
Student student;
public Student this[int index]
{
get { return student; }
set { student = new Student { time = DateTime.Now }; }
}
}
class Client
{
static void Main()
{
StudentMemento s = new StudentMemento();
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
Console.Read();
}
}
根据msdn中的文档,我应该在以下成员s1,s2中获取Student的实例,因为我在Indexer中返回Student对象,但是我得到一个空引用。任何人都可以帮助我理解,为什么会这样。谢谢
答案 0 :(得分:3)
在
null
s.student将是student
。 StudentMemento s = new StudentMemento();
s[1] = null;
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
字段仅在索引器设置器中分配,因此您需要在调用getter之前调用它,例如。
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
folderPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("GameFilesToken", folder);
System.Diagnostics.Debug.WriteLine(folder.Path);
await FileManagementHelper.getFolders(folder.Path);
}
public static async Task<Queue<string>> getFolders(String TopLevel)
{
var Folder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync("GameFilesToken");
var queryResults = Folder.CreateFolderQuery();
var folderList = await queryResults.GetFoldersAsync();
return new Queue<string>();
}