简体   繁体   English

无法通过嵌套类型访问外部类型的非静态成员

[英]Cannot access a nonstatic member of outer type… via nested type

Why do I get this error? 为什么会出现此错误?

Error CS0038: Cannot access a nonstatic member of outer type JsonFeedParserTabs.MainActivity' via nested type JsonFeedParserTabs.MainActivity.SampleTabFragment' (CS0038) (JsonFeedParserTabs) 错误CS0038:无法JsonFeedParserTabs.MainActivity' via nested type JsonFeedParserTabs.MainActivity.SampleTabFragment'(CS0038)(JsonFeedParserTabs)访问外部类型JsonFeedParserTabs.MainActivity' via nested type的非静态成员

I'm trying to put a ListView with json data inside a tab. 我试图将带有json数据的ListView放在选项卡中。

This is my code: 这是我的代码:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Linq;

namespace JsonFeedParserTabs
{
    [Activity (Label = "Feed Reader", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        ListView listView;
//      ProgressBar progressBar;
        RootObject result;

        string url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource.
            SetContentView (Resource.Layout.Main);

            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;

            AddTab (" Tab 1", new SampleTabFragment ());
//          AddTab (" Tab 2", new SampleTabFragment2 ());

            if (bundle != null)
                this.ActionBar.SelectTab(this.ActionBar.GetTabAt(bundle.GetInt("tab")));
        }

        protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex);

            base.OnSaveInstanceState(outState);
        }

        void AddTab (string tabText, Fragment view)
        {
            var tab = this.ActionBar.NewTab ();

            tab.SetText (tabText);

            // Must set event handler before adding tab.
            tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add (Resource.Id.fragmentContainer, view);
            };
            tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs e) {
                e.FragmentTransaction.Remove(view);
            };

            this.ActionBar.AddTab (tab);
        }

        class SampleTabFragment : Fragment
        {
            public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                base.OnCreateView (inflater, container, savedInstanceState);

                var view = inflater.Inflate (Resource.Layout.Tab, container, false);

                // Initializing listView.
                listView = view.FindViewById<ListView> (Resource.Id.listView); // <-- Error!
                listView.ItemClick += OnListItemClick; // <-- Error!

//              progressBar = view.FindViewById<ProgressBar> (Resource.Id.progressBar);
//  
//              // Showing loading progressBar.
//              progressBar.Visibility = ViewStates.Visible;

                // Download and display data in url.
                downloadJsonFeedAsync (url); // <-- Error!

                return view;
            }
        }

//      class SampleTabFragment2 : Fragment
//      {
//          public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//          {
//              base.OnCreateView(inflater, container, savedInstanceState);
//
//              var view = inflater.Inflate(Resource.Layout.Tab, container, false);
//              var sampleTextView = view.FindViewById<TextView>(Resource.Id.sampleTextView);
//
//              sampleTextView.Text = "Sample fragment text 2.";
//
//              return view;
//          }
//      }

        public async void downloadJsonFeedAsync(String url)
        {
            var httpClient = new HttpClient();
            Task<string> contentsTask = httpClient.GetStringAsync(url);

            // Await! control returns to the caller and the task continues to run on another thread.
            string content = await contentsTask;
            Console.Out.WriteLine("Response Body: \r\n {0}", content);

            // Convert string to JSON object.
            result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (content);

            // Update listview.
            RunOnUiThread (() => {
                listView.Adapter = new CustomListAdapter(this, result.posts);
//              progressBar.Visibility = ViewStates.Gone;
            });
        }

        void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Post item = result.posts.ElementAt (e.Position);

            // Passing object form one activity to other.
            Intent i = new Intent(Application.Context, typeof(FeedDetailsActivity));
            i.PutExtra("item", JsonConvert.SerializeObject(item));
            StartActivity(i);
        }
    }
}

I'm stuck and need help, any ideas what I have done wrong and what to do? 我陷入困境,需要帮助,任何想法我做错了什么以及该怎么做? Thank you! 谢谢!

Update 更新资料

Alright it works now but i think there might be a better way to do this. 好的,它现在可以工作,但是我认为可能会有更好的方法来做到这一点。

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Linq;

namespace JsonFeedParserTabs
{
    [Activity (Label = "Feed Reader", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        ListView listView;
//      ProgressBar progressBar;
        RootObject result;

        string url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource.
            SetContentView (Resource.Layout.Main);

            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;

            AddTab (" Tab 1", new SampleTabFragment (this));
//          AddTab (" Tab 2", new SampleTabFragment2 ());

            if (bundle != null)
                this.ActionBar.SelectTab(this.ActionBar.GetTabAt(bundle.GetInt("tab")));
        }

        protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex);

            base.OnSaveInstanceState(outState);
        }

        void AddTab (string tabText, Fragment view)
        {
            var tab = this.ActionBar.NewTab ();

            tab.SetText (tabText);

            // Must set event handler before adding tab.
            tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add (Resource.Id.fragmentContainer, view);
            };
            tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs e) {
                e.FragmentTransaction.Remove(view);
            };

            this.ActionBar.AddTab (tab);
        }

        class SampleTabFragment : Fragment
        {
            private MainActivity context;
            public SampleTabFragment(MainActivity _context) : base()
            {
                this.context = _context;
            }

            public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                base.OnCreateView (inflater, container, savedInstanceState);

                var view = inflater.Inflate (Resource.Layout.Tab, container, false);

                // Initializing listView.
                context.listView = view.FindViewById<ListView> (Resource.Id.listView);
                context.listView.ItemClick += context.OnListItemClick;

//              progressBar = view.FindViewById<ProgressBar> (Resource.Id.progressBar);
//  
//              // Showing loading progressBar.
//              progressBar.Visibility = ViewStates.Visible;

                // Download and display data in url.
                context.downloadJsonFeedAsync (context.url);

                return view;
            }
        }

//      class SampleTabFragment2 : Fragment
//      {
//          public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//          {
//              base.OnCreateView(inflater, container, savedInstanceState);
//
//              var view = inflater.Inflate(Resource.Layout.Tab, container, false);
//              var sampleTextView = view.FindViewById<TextView>(Resource.Id.sampleTextView);
//
//              sampleTextView.Text = "Sample fragment text 2.";
//
//              return view;
//          }
//      }

        public async void downloadJsonFeedAsync(String url)
        {
            var httpClient = new HttpClient();
            Task<string> contentsTask = httpClient.GetStringAsync(url);

            // Await! control returns to the caller and the task continues to run on another thread.
            string content = await contentsTask;
            Console.Out.WriteLine("Response Body: \r\n {0}", content);

            // Convert string to JSON object.
            result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (content);

            // Update listview.
            RunOnUiThread (() => {
                listView.Adapter = new CustomListAdapter(this, result.posts);
//              progressBar.Visibility = ViewStates.Gone;
            });
        }

        void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Post item = result.posts.ElementAt (e.Position);

            // Passing object form one activity to other.
            Intent i = new Intent(Application.Context, typeof(FeedDetailsActivity));
            i.PutExtra("item", JsonConvert.SerializeObject(item));
            StartActivity(i);
        }
    }
}

It's telling you exactly what it can't do. 它正在告诉您确切它不能做什么。 The MainActivity members are not accessible from the fragment types declared within the MainActivity type. MainActivity成员不是从内声明的片段类型的访问MainActivity类型。 So when you try to call downloadJsonFeedAsync (url); 因此,当您尝试调用downloadJsonFeedAsync (url); it fails because it's not a static (class) method. 它失败,因为它不是静态(类)方法。 The fragments (although declared within the type), do not exist within an instance of the MainActivity type. 片段(尽管在类型中声明了)在MainActivity类型的实例中不存在。

Unless there's some compelling reason for them to remain within the MainActivity type, I'd move them out. 除非有令人信服的理由让它们保留在MainActivity类型内,否则我将其移出。 They should also then have a reference to the MainActivity type so that you can call downloadJsonFeedAsync(string) on it. 然后,他们还应该引用MainActivity类型,以便可以在其上调用downloadJsonFeedAsync(string)

On an unrelated note (and I appreciate this is very much uninvited commentary :) ), you may want to consider using a MVVM pattern. 无关紧要的是(我很欣赏这是不受欢迎的评论:)),您可能需要考虑使用MVVM模式。 It looks like you're intermixing presentation, application control, and business data. 看起来您正在混合演示文稿,应用程序控制和业务数据。 If this app grows beyond the one or two pages, you will find much peace in segregating responsibilities. 如果此应用程序扩展到一页或两页之外,则可以轻松地分担责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法访问外部类型的非静态成员 - Cannot access a nonstatic member of outer type 无法通过嵌套类型访问外部类型的非静态成员 - Cannot access a non-static member of outer type via nested type 无法通过嵌套类型“FormMain.ImageDelegateClass”访问外部类型“FormMain”的非静态成员 - Cannot access a non-static member of outer type 'FormMain' via nested type 'FormMain.ImageDelegateClass' 无法通过嵌套类型X访问外部类型X的非静态成员 - Cannot access a non-static member of outer type X via nested type X 无法使用第三方提供的类通过嵌套类型访问外部类型XXX的非静态成员 - Cannot access a non-static member of outer type XXX via nested type with a third-party provided class 使标签静态错误:无法通过嵌套类型“windowsForm8.Form1.DBConnect”访问外部类型“windowsForm8.Form1”的非静态成员 - make a label static error : cannot access a non-static member of outer type 'windowsForm8.Form1' via nested Type 'windowsForm8.Form1.DBConnect' 无法访问外部类型的非静态成员 - Cannot access a non-static member of outer type C#无法访问外部类型的非静态成员 - C# cannot access a non-static member of outer type 避免“通过派生类型访问类型的静态成员” - Avoiding “Access to a static member of a type via a derived type” 无法通过RIA服务访问EntityObject类型 - Cannot access EntityObject type via RIA services
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM