从控制器调用列表类

如何从控制器调用我的班级列表?


这是我的模型:


public class AuthJsonResponses

{

    public int Code { get; set; }

    public string Jwt { get; set; }

    //public string[] Message { get; set; }

    public List<RootObject> Message { get; set; }

}


public class RootObject

{

    public string msg { get; set; }

    public string code { get; set; }

}

这就是我在控制器中调用的:


List<RootObject> rootObj = new List<RootObject>();

rootObj[0].code = "success_04";

rootObj[0].msg = "Access granted";

JsonRes.Message = rootObj;

但是,我不知道的范围似乎存在问题。我的代码有什么问题?


慕侠2389804
浏览 101回答 5
5回答

素胚勾勒不出你

您可以执行以下操作之一:&nbsp;List<RootObject> rootObj = new List<RootObject>();&nbsp; &nbsp; &nbsp; &nbsp; var newObj=new RootObject()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; code = "success_04",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; msg = "Access granted"&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; rootObj.Add(newObj);&nbsp; &nbsp; &nbsp; &nbsp; List<RootObject> rootObj1 = new List<RootObject>()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new RootObject()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; code = "success_04",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; msg = "Access granted"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };接着JsonRes.Message = rootObj;

繁花如伊

您正在像处理数组一样处理列表,这是行不通的,您需要使用该Add方法,例如rootObj.Add(new RootObj{&nbsp; &nbsp; code = "success_04",&nbsp; &nbsp; msg = "Access granted"});您还可以使用该AddRange方法添加多个对象,例如rootObj.AddRange(new List<RootObj>{new RootObj{&nbsp; &nbsp; code = "success_04",&nbsp; &nbsp; msg = "Access granted"}, new RootObj{&nbsp; &nbsp; code = "success_05",&nbsp; &nbsp; msg = "Access denied"}});

互换的青春

直接访问您的AuthJsonResponses实例。首先,更新该类以使其Message具有私有设置器并将其实例化为List<RootObject>public class AuthJsonResponses{&nbsp; &nbsp; public int Code { get; set; }&nbsp; &nbsp; public string Jwt { get; set; }&nbsp; &nbsp; public List<RootObject> Messages { get; private set; } = new List<RootObject>();}public class RootObject{&nbsp; &nbsp; public string msg { get; set; }&nbsp; &nbsp; public string code { get; set; }}在您的代码中,直接将对象添加到Message属性中。我建议将其重命名为Messages以表明它是一个集合jsonRes.Messages.Add(new RootObject{msg ="Access granted", code="success_04"});

偶然的你

您面临的问题是您在初始化列表之后引用列表的第一个元素!初始化本身只是创建List类的对象,它不创建任何元素!因此,您必须自己创建RootObject类的对象,然后将其添加到列表中:// create objectvar r = new RootObject();r.code = "success_04";r.msg = "Access granted";// add it to listrootObj.Add(r);

叮当猫咪

当您List实际使用时,您可以使用从类继承的方法IEnumerable,因为 List 是 IEnumerable 的实现。你可以这样做:List<RootObject> rootObj = new List<RootObject>();//delete this---- rootObj[0].code = "success_04";//delete this---- rootObj[0].msg = "Access granted";//use thisrootObj.Add(new RootObject{code = "success_04",msg = "Access Granted"})JsonRes.Message = rootObj;
打开App,查看更多内容
随时随地看视频慕课网APP