访问财产时出现问题



在很短的时间内得到大家的帮助。通过重写 toString 方法解决了该问题。

我有以下问题:(已解决(

public class CryptoApiResponse
{
    [DeserializeAs(Name = "ticker")]
    public List<CryptoAttributes> CryptoCurrency { get; set; }
    public override string ToString()
    {
        return $"Currency:{CryptoCurrency[0].Currency} " +
               $"PriceFiat:{CryptoCurrency[0].PriceFiat} " +
               $"Fiat:{CryptoCurrency[0].TargetFiat}";
    }
}
public class CryptoAttributes
{
    [DeserializeAs(Name = "base")]
    public string Currency { get; set; }
    [DeserializeAs(Name = "target")]
    public string TargetFiat { get; set; }
    [DeserializeAs(Name = "price")]
    public string PriceFiat { get; set; }
}

我想访问以下内容:

public void Display<CryptoApiResponse>(List<CryptoApiResponse> apiList)
{
    if (apiList != null)
    {
        foreach (CryptoApiResponse cryptoCurrency in apiList)
        {
            Console.WriteLine(cryptoCurrency.ToString());
        }
    }
    Console.ReadLine();
}
Console.WriteLine(obj);
// this means more or less the following
Console.WriteLine(obj.ToString());
// this means you should override the ToString() method
// or to make a custom string

您正在循环访问一个列表,并且每个加密中都存在一个子列表列表。简而言之,你得到列表>。

当您 foreach 此列表时,您可能需要使用第二个 foreach 来迭代子列表中的值以访问您的属性。

foreach (var crypt in crypto)
{
  foreach (var basedata in crypt.Ticker)
  {
    Console.WriteLine($"Currency:{basedata.Currency} Price: {basedata.Price} Target: {basedata.Target}");
  }
}

如果您保留链接的 API 的命名并区分列表和单个对象名称,将更容易理解问题所在。类应该看起来像这样(注意TickerTickers之间的区别

public class Crypto
{
    public List<Ticker> Tickers { get; set; }
}
public class Ticker
{
    public string Currency { get; set; }
    public string Target { get; set; }
    public string Price { get; set; }
}

Display中的参数crypto(应cryptos(是一个列表,Tickers是一个列表,因此您需要嵌套循环。您还应该从 methos 签名中删除 Crypto 参数,因为它隐藏了Crypto

public void Display(List<Crypto> cryptos)
{
    foreach (Crypto crypto in cryptos)
    {
        foreach (Ticker ticker in crypto.Tickers)
        {
            Console.WriteLine(ticker);
        }
    }
}

或者,如果您想使用部分 Linq

public void Display(List<Crypto> cryptos)
{
    foreach (Ticker ticker in cryptos.SelectMany(crypto => crypto.Tickers))
    {
        Console.WriteLine(ticker);
    }
}

你能在循环时尝试使用"加密"而不是"var"吗?我的意思是这样做。我记得VS2015之前的版本(可能是VS2010(,如果我们使用"var",变量的类型将被视为对象。

public void Display<Crypto>(List<Crypto> crypto)
{
    if (crypto != null)
    {
        // Currency, Target and Price
        foreach (***Crypto*** ticker in crypto)
        {
            Console.WriteLine(ticker); // ticker Type Crypo
            // ticker.Ticker
        }
    }
    Console.ReadLine();
}

最新更新