C# 从 class 实例化 IList 对象并在一行中设置本地属性

C# Instantiate IList object from a class and set local properties in one line

嘿美妙的Whosebugers, 我在使用属于 class 的 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} } 

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

提前致谢

你想实现这样的目标吗?

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

所以我把头埋在了 JSON 序列化的实际需求上,而没有考虑列表。

想到这个

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

所以我可以创建另一个字符串数组实例,它适用于我需要的 json 输出。感谢@neelesh 的提示,我才知道这个!