如何从不同的函数访问返回的对象 & class

How to access returned object from different function & class

我有一个 C# 应用程序,一旦您按下按钮,它就会向 Web API 发送 Web 请求并检索所有 Json 值。然后将它们反序列化为一个对象,并 returned 到函数被调用的地方。

现在我正在尝试访问从另一个 class 中的 GetApi 函数 returned 的对象。

Cannot implicitly convert type 'object' to 'GW2_tradingPost.Listings'. An explicit conversion exists (are you missing a cast?) line 32

我知道我做错了,但我无法理解哪里出了问题

Form1.cs

private void button1_Click(object sender, EventArgs e)
    {
        Listings Listings = new Listings();
        api_Request api_Request = new api_Request();

        Listings richTextBox1 = api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings/19684");
    }

api_Request.cs

public class api_Request
    {
        public Object GetApi(string url)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    //StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    //return reader.ReadToEnd();
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    var jsonReader = new JsonTextReader(reader);
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<Listings>(jsonReader);
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

    }

    public class Listings
    {
        [JsonProperty(PropertyName = "id")]
        public int Id { get; set; }

        public List<Buy> Buys { get; private set; }

        public Listings()
        {
            Buys = new List<Buy>();
        }
    }
    public class Buy
    {
        [JsonProperty(PropertyName = "listings")]
        public int Listings { get; set; }

        [JsonProperty(PropertyName = "unit_price")]
        public int UnitPrice { get; set; }

        [JsonProperty(PropertyName = "quantity")]
        public int Quantity { get; set; }
    }

我正在使用它来调用对象,return 消息框中的一个值,但它的 returning 0 应该是 19684。

api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings/19684"); MessageBox.Show(Listings.Id.ToString());

您的签名是Object GetApi(string url)。将其更改为 Listings GetApi(string url),因为这就是您从该方法中实际 return 的内容。

还可以考虑为 "GetApi" 方法指定一个更合理的名称,以说明它的实际作用。