同じクラス内の関数で変数宣言クラスを使用できません。なぜ ?

StackOverflow https://stackoverflow.com/questions/4078285

  •  28-09-2019
  •  | 
  •  

質問

「Context2」という名前のクラス「メイン」の変数を宣言しました。ただし、関数「main_load」内の変数を使用することはできません。私は何が間違っているのですか?

using System;
using System.Windows.Forms;
using Soapi;
using Soapi.Domain;

namespace SO_Console_Client
{
    public partial class Main : Form
    {
        const string apiKey = "*************";
        var context2 = new ApiContext(apiKey).Initialize(false);
        public Main(String GravatarURL, User user)
        {
            InitializeComponent();
            pictureBox1.Load(GravatarURL);  //Loads the Gravatar image from the url

            //set the reputation details
            lblRep.Text = String.Format("Reputation: {0}", user.Reputation);

            //Sets the badge details
            lblBadge.Text = String.Format("Badges: gold={0} silver={1} bronze={2}", user.BadgeCounts.Gold, user.BadgeCounts.Silver, user.BadgeCounts.Bronze);

            groupBox1.Text = user.DisplayName.ToString();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            Soapi.Queries.QuestionsUnansweredQuery query = context2.Official.StackOverflow.Questions.Unanswered;
            foreach (Question q in query)
            {
                try
                {
                    Console.WriteLine(q.Title.ToString());
                    //Console.WriteLine(q.Body.ToString());
                }
                catch (System.NullReferenceException ex)
                {

                }

            }

        }
    }
}
役に立ちましたか?

解決

暗黙のタイピングはフィールドでは機能しません。ローカル変数でのみ動作します。

考える これがあなたの本当の意図です:

ApiContext context2 = new ApiContext(apiKey);

public Main(String GravatarURL, User user)
{
   context2.Initialize(false);
   ...
}

非常にありそうもないケースで ApiContext ある種の流entなインターフェイスです ApiContext.Initialize(bool)返品a 違うApiContextオブジェクト、これはあなたが望むものでなければなりません:

ApiContext context2 = new ApiContext(apiKey).Initialize(false); 

あなたがした場合、それははるかに明確ですが:

ApiContext context2;

public Main(String GravatarURL, User user)
{
   context2 = new ApiContext(apiKey).Initialize(false);
   ...
}

しかし、私はそれを本当に疑っています。

他のヒント

これはコンパイルできません。 var-Type変数宣言はクラスレベルではなく、メソッドレベルのみをレベルにすることはできません。

VARをフィールドで使用できるようにするには、技術的な問題があります。これが、コンクリートタイプを指定する必要がある理由です。エリック・リパートの問題の説明は次のとおりです。

フィールドにvarがない理由

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top