【问题标题】:CS0120 An object reference is required for the non-static field, method, or property 'Group.Title'CS0120 非静态字段、方法或属性“Group.Title”需要对象引用
【发布时间】:2017-12-16 16:07:52
【问题描述】:

我的 UWP 应用出现问题,我创建了一个收藏夹页面,该页面允许用户重新排序并保存页面上的数据。我两次遇到同样的错误

CS0120 非静态字段、方法或属性“Group.Title”需要对象引用

CS0120 非静态字段、方法或属性“Group.Items”需要对象引用

谁能给我解释一下为什么会这样? 谢谢。

CS 文件


using App1.Common;
using App1.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Json;


namespace App1
{

public sealed partial class test : Page
{
    public ObservableCollection<ItemData> Items { get; set; }

    private ObservableDictionary defaultViewModel = new 
    ObservableDictionary();
    private NavigationHelper navigationHelper;
    private RootObject jsonLines;
    private StorageFile fileFavourites;
    private Dictionary<string, ItemData> ItemData = new Dictionary<string, 
    ItemData>();


    public test()
    {
    loadJson();
    getFavoritesFile();

    this.InitializeComponent();
    this.navigationHelper = new NavigationHelper(this);
    this.navigationHelper.LoadState += navigationHelper_LoadState;
    }

    void ItemView_ItemClick(object sender, ItemClickEventArgs e)
    {
        // Navigate to the appropriate destination page, configuring the new 
        page
        // by passing required information as a navigation parameter
        var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
        this.Frame.Navigate(typeof(GroupedItemsPage), itemId);
    }

    private void setupObservableCollection()
        {
            Items = new ObservableCollection<ItemData>(ItemData.Values);
            itemGridView.ItemsSource = Items;
        }

        private async void loadJson()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new 
            Uri("ms-appx:///DataModel/SampleData.json"));
            var lines = await FileIO.ReadTextAsync(file);
            jsonLines = JsonConvert.DeserializeObject<RootObject>(lines);
            feedItems();
        }

        private async void getFavoritesFile()
        {
            Windows.Storage.StorageFolder storageFolder = 
            Windows.Storage.ApplicationData.Current.LocalFolder;
            fileFavourites = await storageFolder.GetFileAsync("Fav.txt");
        }

        private async void feedItems()
        {
            if (await FileIO.ReadTextAsync(fileFavourites) != "")
            {
                foreach (var line in await 
                FileIO.ReadLinesAsync(fileFavourites))
                {
                    foreach (var Group in jsonLines.Groups)
                    {
                    foreach (var Item in Group.Items)
                    {
                        if (Item.UniqueId == line)
                        {
                            var storage = new ItemData()
                            {
                                Title = Item.Title,
                                UniqueID = Item.UniqueId,
                                ImagePath = Item.ImagePath,
                                Group = Group.Title
                            };
                            ItemData.Add(storage.UniqueID, storage);
                        }
                    }
                }
                }
            }
            else
            {//if favourites file is empty, use?
            foreach (var Group in jsonLines.Groups) ;
            {
                foreach (var Item in Group.Items)
                {
                    var storage = new ItemData()
                    {
                        Title = Item.Title,
                        UniqueID = Item.UniqueId,
                        ImagePath = Item.ImagePath,
                        Group = Group.Title
                    };
                    ItemData.Add(storage.UniqueID, storage);
                    await FileIO.AppendTextAsync(fileFavourites, 
                    Item.UniqueId + "\r\n");
                }
            }
        }


        setupObservableCollection();
        }


        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        #region NavigationHelper loader

        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        private async void MessageBox(string Message)
        {
            MessageDialog dialog = new MessageDialog(Message);
            await dialog.ShowAsync();
        }

        private async void navigationHelper_LoadState(object sender, 
        LoadStateEventArgs e)
        {
            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            this.defaultViewModel["Groups"] = sampleDataGroups;
        }

        #endregion NavigationHelper loader

        #region NavigationHelper registration

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        #endregion NavigationHelper registration
    }

    public class ItemData
    {
        public string UniqueID { get; set; }
        public string Title { get; set; }
        public string Group { get; set; }
        public string ImagePath { get; set; }
    }

}

根对象文件

using App1.Data;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace App1
{

public class Item
{
    public string UniqueId { get; set; }
    public string Title { get; set; }
    public string Subtitle { get; set; }
    public string ImagePath { get; set; }
    public string Description { get; set; }
    public string Content { get; set; }
}

public class Group
{
    public string UniqueId { get; set; }
    public string Title { get; set; }
    public string Subtitle { get; set; }
    public string ImagePath { get; set; }
    public string Description { get; set; }
    public List<Item> Items { get; set; }
}

public class RootObject
{
    public List<Group> Groups { get; set; }
}  
}

【问题讨论】:

  • 您将面临的另一个问题是您尝试设置 foreach 迭代变量的值。

标签: c# uwp json.net


【解决方案1】:

问题出现在您的foreach 循环中。其实有两个问题:

  1. 您使用Group 作为迭代变量,这是可能的,但会导致与类名Group 混淆。
  2. 实例化new ItemData时,突然用Group.Title代替Item.Title

所以循环的更正版本可能如下所示:

foreach (var group in jsonLines.Groups) ;
{
    foreach (var item in group.Items)
    {
        var storage = new ItemData()
        {
            Title = item.Title,
            UniqueID = item.UniqueId,
            ImagePath = item.ImagePath,
            Group = item.Title
         };
         ItemData.Add(storage.UniqueID, storage);
         await FileIO.AppendTextAsync(fileFavourites, 
                Item.UniqueId + "\r\n");
     }
 }

我将循环变量Group 更改为小写group。我将第二个循环变量Item 也更改为小写,这在您的情况下不是必需的,但更好地符合C# naming conventions

【讨论】:

  • 嗨,这解决了所有问题,但我仍然在“group.items”上收到错误
  • @Chuggingtonss 你注意到它必须是group.Items,而不是Group.Items吗?注意外壳。
  • @Chuggingtonss 我刚刚看到你有第二个循环有同样的问题。我认为我的解释也应该可以帮助您修复该循环:)
  • 在第一个 foreach 语句后愚蠢地加了一个逗号,似乎已经奏效了,谢谢
【解决方案2】:

在您的 foreach 中,您应该使用其他名称而不是 Group,因为它与类的名称冲突。小写组将起作用。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多