0

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?

kace91
  • 821
  • 1
  • 10
  • 23
  • 2
    I think you actually should be using [composition instead of inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance). – juharr Feb 16 '16 at 16:42
  • @juharr Yeah this is probably not the perfect solution for my current problem, but regardless, is there any way to do this reference? Out of curiosity. – kace91 Feb 16 '16 at 16:44

2 Answers2

0

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

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

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.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71