4
using System;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace LearningJustCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Update();
        }

        static void Update()
        {
            var quote1 = new { Stock = "DELL", Quote = GetQuote("DELL") };
            var quote2 = new { Stock = "MSFT", Quote = GetQuote("MSFT") };
            var quote3 = new { Stock = "GOOG", Quote = GetQuote("GOOG") };

            var quotes = new object[] { quote1, quote2, quote3 };

            foreach (var item in quotes)
            {
                Console.WriteLine(item.Stock);
                Console.WriteLine(item.Quote.ToString());
            }
        Console.ReadKey();

        }

        static string GetQuote(string stock)
        {
            try
            {
                return InnerGetQuote(stock);
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
                return "N/A";
            }
        }

        static string InnerGetQuote(string stock)
        {
            string url = @"http://www.webservicex.net/stockquote.asmx/GetQuote?symbol={0}";
            var request = HttpWebRequest.Create(string.Format(url, stock));

            using (var response = request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                {
                    return reader.ReadToEnd();
                }
            }


        }
    }
}

我在项目上得到一个波浪线;变量“项目”仅分配给。此代码已根据 Paul Kimmel 的书 C# Unleashed by Sams 稍作修改。

4

2 回答 2

12

您的数组必须是您的股票报价的类型。您的股票报价是匿名类型,因此我们也需要匿名定义数组。这可以干净地完成为:

    var quotes = new[]{  new { Stock = "DELL", Quote = "123" },
                         new { Stock = "MSFT", Quote = "123" },
                         new { Stock = "GOOG", Quote = "123" }};

    foreach (var item in quotes)
    {
        Console.WriteLine(item.Stock);
        Console.WriteLine(item.Quote.ToString());
    }
于 2012-05-21T22:21:38.633 回答
5

我想问题出在那一行:

var quotes = new object[] { quote1, quote2, quote3 };

引号是一个对象数组,而不是该匿名类型的数组。foreach 也只有对象值。您可以尝试在一行或 lambda 表达式中形成数组

一个非常肮脏的解决方法是将“var”更改为“动态”

        var quote1 = new { Stock = "DELL", Quote = ("DELL") };
        var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
        var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };

        var quotes = new object[] { quote1, quote2, quote3 };

        foreach (dynamic item in quotes)
        {
            var r = item.Stock;

        }

一个更干净的解决方案是省略“对象”,因此编译器可以生成一个匿名类型数组

        var quote1 = new { Stock = "DELL", Quote = ("DELL") };
        var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
        var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };

        var quotes = new [] { quote1, quote2, quote3 };

        foreach (var item in quotes)
        {
            var r = item.Stock;

        }
于 2012-05-21T22:02:27.043 回答