嘿,很棒的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} }
有什么好办法来解决这个问题? 请引导我进入最合适的解决方案。
事先谢谢你
你想要达到这样的目标吗?
new RequestFieldValues()
.customfield_10304 = new List<Customfield>
{
new Customfield{id ="id1", self = "Sefd1", value = "value1"},
new Customfield{id ="id2", self = "Sefd2", value = "value2"}
};
使用反射或使用反射的序列化,例如(无法编译-语法可能有点错误,但此计算机上没有安装VS,使用Intellisense和MS Doc.网站应该很容易修复)。
var result = myObj.GetClass().Properties().Select(p =>
new KeyValuePair<String, Object>(
p.PropertyName,
p.Getter.Invoke(myObj, new object[0])
)
);
您可以在末尾添加。toList()或。toDictionary()。