【问题标题】:C# Instantiate IList object from a class and set local properties in one lineC# 从一个类中实例化 IList 对象并在一行中设置本地属性
【发布时间】:2020-06-18 14:30:28
【问题描述】:

嘿,美妙的 stackoverflowers, 我在使用作为类的一部分的 IList 对象时遇到了一些问题。 稍后它将被序列化为 JSON,其中要求它将在 customfield_10304 对象内生成一个包含键值对的数组。

习惯于使用字典来实现类似的目的,我在尝试使用 IList 做类似的事情但失败了。

            public class Customfield
            {
                public string self { get; set; }
                public string value { get; set; }
                public string id { get; set; }
            }
            public class RequestFieldValues
            {
                public IList<Customfield> customfield_10304 { get; set; }
            }

/* NOTE: This is how I THINK it should work in my mind, but it is throwing errors */
var customfield_10304 = new IList<string> { {value = "test", id = 0} } 

解决这个问题的好方法是什么?请指导我找到最合适的解决方案。

提前谢谢你

【问题讨论】:

  • 你不能创建接口的实例。尝试创建一个实现 IList 的类的实例,例如 List。查看 documentation 了解实现 IList 的类
  • 要序列化成 JSON,请参考这些链接 newtonJsonSerialization in .NET。此外,JSON 序列化会生成与 Dictionary 不同的键值对。

标签: c# list instantiation


【解决方案1】:

您是否正在尝试实现这样的目标?

        new RequestFieldValues()
            .customfield_10304 = new List<Customfield>
            {
                new Customfield{id ="id1", self = "Sefd1", value = "value1"},
                new Customfield{id ="id2", self = "Sefd2", value = "value2"}
            };

【讨论】:

    【解决方案2】:

    所以我有点绕着 JSON 序列化的实际需求,跳过了对列表的思考。

    想出了这个

    public Customfield[] customfield_10304 { get; set; }
    requestFieldValues = new RequestFieldValues
                    {
                        customfield_10304 = new Customfield[] 
                            {
                                new Customfield { value = "Other" }
                            }
                    }
    

    所以我可以创建另一个字符串数组实例,它适用于我需要的 json 输出。多亏了@neelesh 提示,我才发现了这一点!

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2012-07-31
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多