Say that I have a public class MyClass: List<MyObjects>
.
I want this class to have an inner method that manipulates the list, say
void ConstructListFromJSON(){
HoweverIshouldrefertomylist = JsonUtility.FromJson<List<MyObjects>("myObjects.json");
}
What should I put in place of the HoweverIshouldrefertomylist ? I've tried this
, self
and similar but it doesn't work. Surely there's a way to refer to the data strucure in the list?
You cannot reassign this
, so clear the list and add whatever you want to add:
var objectsToStore = JsonUtility.FromJson<List<MyObjects>>("myObjects.json");
this.Clear();
this.AddRange(objectsToStore);
But in general, you really don't want to inherit from List<T>
. See Why not inherit from List<T>? . Use composition instead:
public class MyClass
{
public List<YourObjects> YourObjects { get; set; }
public void ConstructListFromJSON()
{
YourObjects = JsonUtility.FromJson<List<MyObjects>("myObjects.json");
}
}
To properly generate classes representing your JSON, see Deserializing JSON into an object
To access a base object, just use the base keyword. But, for what you are showing, a different approach makes more sense - - just maintain a private object reference.
public class foo{
private List<MyObject> myList = null;
public foo(List<MyObject> l){
myList = l;
}
}
Now, the class has the list upon construction, but the list is private to the user. This is a better form of design. It uses composition over inheritance and provides a more loosely coupled design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.