简体   繁体   English

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

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

Hey wonderful stackoverflowers, I'm having some trouble with the IList object that is part of a class.嘿,美妙的 stackoverflowers,我在使用 IList object 时遇到了一些问题,它是 class 的一部分。 It will later be serialized into JSON where the requirement is that it will produce an array with key value pairs inside of the customfield_10304 object.稍后它将被序列化为 JSON,其中要求它将生成一个数组,其中包含 customfield_10304 object 内的键值对。

Being used to working with Dictionaries for the similar purpose I'm trial-and-erroring away at doing something similar with an IList but failing.习惯于为类似目的使用字典,我在尝试和错误地使用 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} } 

What's a good way to approach this?解决这个问题的好方法是什么? Please guide me into the most appropriate solution.请指导我找到最合适的解决方案。

Thank you in advance先感谢您

Are you trying to achieve something like this?你想达到这样的目标吗?

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

So I kind of wrapped my head around the actual requirement of the JSON serialization and skipped thinking about Lists.所以我有点绕着 JSON 序列化的实际需求,跳过了对列表的思考。

Came up with this想出了这个

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

So I could make another instance of a String array and that works for the json output that I needed.所以我可以创建另一个字符串数组实例,它适用于我需要的 json output。 It is thanks to @neelesh tip that I found out about this!多亏了@neelesh 提示,我才发现了这一点!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM