【问题标题】:C# how to check array in listC#如何检查列表中的数组
【发布时间】:2021-06-04 10:03:39
【问题描述】:

我正在为 Windows 构建一个 Worker 服务,该服务从系统上的另一个程序获取数据。 此时我拥有所有需要的数据,现在我想保留一个包含最新数据的列表。 当我为区域运行应用程序时,我得到System.Int32[] 我希望看到的是来自System.Int32[] 的数据

如何获得?

List<BroadcastModel> activeOmroep = new List<BroadcastModel>();

for (int o = 0; o < webcontent.Length; o++)
        {
       
            for (int i = 0; i < webcontent[o].Zones.Length; i++)
            {
                
            }
            
            activeOmroep.Add(new BroadcastModel
            {
                Id = webcontent[o].Id,
                Name = webcontent[o].Name,
                Recording = webcontent[o].Recording,
                Zones = webcontent[o].Zones
            }) ;

我的BroadcastModel 类如下所示:

public class BroadcastModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int[] Channels { get; set; }
    public bool Recording { get; set; }
    public int Type { get; set; }
    public int Volume { get; set; }
    public int[] Zones { get; set; }
}

提前致谢。

出于测试目的,我添加了以下内容:

foreach (var omroep in activeOmroep)
        {
            Console.WriteLine("Broadcast ID: " + omroep.Id);
            Console.WriteLine("Broadcast Name: " + omroep.Name);
            Console.WriteLine("Broadcast is recording: " + omroep.Recording);
            Console.WriteLine("Broadcast Zones: " + omroep.Zones);
            Console.WriteLine("****************************");
        }

但后来我得到了 system.int32[]

【问题讨论】:

  • 您在代码的哪一部分遇到了问题?
  • @TonyStark 我编辑了我的问题..也许有帮助..

标签: c# list model


【解决方案1】:

每当您使用Console.WriteLine() 打印数据时,它都会调用.ToString() 方法,如果.ToString() 未被覆盖,则它会调用Object.ToString() 方法。 Object.ToString() 以字符串格式打印类型。

在您的情况下,Console.WriteLine("Broadcast Zones: " + omroep.Zones); 正在打印 System.Int32[],因为它正在使用基本行为调用 ToString() 方法。

为了解决您的问题,我建议在BroadcastModel 类中使用Override ToString() 方法并返回您要打印的字符串。

要打印数组元素,请使用string.Join() 方法。

连接指定数组的元素或数组的成员 集合,在每个元素之间使用指定的分隔符或 会员。

public class BroadcastModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int[] Channels { get; set; }
    public bool Recording { get; set; }
    public int Type { get; set; }
    public int Volume { get; set; }
    public int[] Zones { get; set; }

    public override string ToString()
    {
       return $"ID : {this.Id}, \nName: {this.Name} \nIs recording: {this.Recording} \nZones : {string.Join(", ", this.Zones)}";
    }
}

现在您可以使用foreach 循环打印List&lt;BroadcastModel&gt;

foreach(var broadcastmodel in activeOmroep)
   Console.WriteLine(broadcastmodel);

【讨论】:

  • @SanderBloem,我更新了我的答案,让您更清楚地了解您为什么收到System.Int32[]
猜你喜欢
  • 2021-12-10
  • 1970-01-01
  • 2017-11-17
  • 2022-12-06
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多