变量返回空

时间:2015-01-12 01:27:07

标签: c# variables null collectionview

我有一个CollectionView,在里面我有一个从一个位置读取文件的方法,一旦读取,就意味着将它添加到变量中。这是我的代码:

class Cvs
{
    static string x1, x2, x3;
    public class Items
    {
        public string ItemID { get; set; }
        public string ItemTitle { get; set; }
        public string ItemBody { get; set; }
    }

    public class ItemList
    {
        List<Items> item = new List<Items>();
        public ItemList()
        {
            ReadStuff();

            item.Add(new Items() { ItemID = x1, ItemTitle = x2, ItemBody = x3 });
        }
        public List<Items> GetitemList()
        {
            return item;
        }
    }

    public async static void ReadStuff()
    {
        var AppStorage = ApplicationData.Current.LocalFolder;
        var itemFolders = await AppStorage.GetFolderAsync(@"App\Folder\");
        var Items = await itemFolders.GetFoldersAsync();
        foreach (var itemFolder in Items)
        {
            var itemTitle = await AppStorage.GetFileAsync(string.Format(@"App\Folder\{0}\Title.txt", itemFolder.Name));
            var itemBody = await AppStorage.GetFileAsync(string.Format(@"App\Folder\{0}\Body.txt", itemFolder.Name));

            var itemReadTitle = await FileIO.ReadTextAsync(itemTitle);
            var itemReadBody = await FileIO.ReadTextAsync(itemBody);

            x1 = itemFolder.Name;
            x2 = itemReadTitle;
            x3 = itemReadBody;
        }
    }
}

它应该做的是阅读这些文件,当它发生时,它意味着将其添加到x1x2x3然后x1,{{ 1}}和x2被添加到:

x3

即使文件不为空,最终结果仍为空。我该如何解决?

2 个答案:

答案 0 :(得分:2)

你没有等待ReadStuff()

public ItemList()
{
    Initialize();
}

public async void Initialize()
{
    await ReadStuff();
    item.Add(new Items() { ItemID = x1, ItemTitle = x2, ItemBody = x3 });
}

您必须将ReadStuf从void更改为Task

答案 1 :(得分:0)

1)您必须await ReadStuff()

2)因为ReadStuff正在迭代,所以设置静态(x变量)将不起作用。更改ReadStuff以将项目添加到列表中。

public async static void ReadStuff(List<Items> items)
{
    var AppStorage = ApplicationData.Current.LocalFolder;
    var itemFolders = await AppStorage.GetFolderAsync(@"App\Folder\");
    var Items = await itemFolders.GetFoldersAsync();
    foreach (var itemFolder in Items)
    {
        var itemTitle = await AppStorage.GetFileAsync(string.Format(@"App\Folder\{0}\Title.txt", itemFolder.Name));
        var itemBody = await AppStorage.GetFileAsync(string.Format(@"App\Folder\{0}\Body.txt", itemFolder.Name));

        var itemReadTitle = await FileIO.ReadTextAsync(itemTitle);
        var itemReadBody = await FileIO.ReadTextAsync(itemBody);

        x1 = itemFolder.Name;
        x2 = itemReadTitle;
        x3 = itemReadBody;

       items.Add(new Items() { ItemID = x1, ItemTitle = x2, ItemBody = x3 });
    }
}