gpt4 book ai didi

c# - 如何将列表填充为类对象?

转载 作者:行者123 更新时间:2023-11-30 23:29:50 28 4
gpt4 key购买 nike

如何将列表填充为类对象?例如,这不起作用:

[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}

public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}

public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}

public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}

这是 Controller Action :

public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();

List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;

List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;

return jsonReviewFormFields;
}

代码崩溃在

jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort;

这可能是一个基本的面向对象错误。您如何填充列表?

最佳答案

你不是在实例化它,你必须先实例化类型:

jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();

然后设置它的属性:

jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort

在此之前,您还必须实例化主类,我在任何地方的 Controller 操作中都看不到它:

JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();

关于c# - 如何将列表填充为类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208982/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com