简体   繁体   中英

C# Run a method of object in an ArrayList

I have bulb.cs in a directory:

class Bulb{
  private state = 0;
  public void printState(){
    Console.Writeln("State = " + state);
  }
}

I am using it in main.cs in a class called MainClass:

using System;
using System.Collections;

class MainClass {
  private ArrayList bulbs = new ArrayList();

  public static void Main (string[] args) {
    MainClass m = new MainClass();
    m.beginSimulation();
  }
  public void beginSimulation(){
    for(int i=0;i<10;i++){
       bulbs.Add(new Bulb());
    }
    for(int i=0;i<10;i++){
       bulbs[i].printState();
    }
  }
}

When I run main.cs in repl.it I get this error:

mcs -out:main.exe bulb.cs main.cs main.cs(16,17): error CS1061: Type object' does not contain a definition for printState' and no extension method printState' of type object' could be found. Are you missing an assembly reference? /usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error) Compilation failed: 1 error(s), 0 warnings compiler exit status 1

The "main.cs(16,17)" is referring to the line "bulbs[i].printState();".

In Java you could do "bulbs.get(i).printState() and it would execute the method. In C# I can't figure it out and I have to use ArrayList instead of List to do this.

I know you can use

foreach(Bulb l in bulbs){
  l.printState();
}

But I don't get why you can't access the method by the index like the documentation says that you can: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.item?view=netcore-3.1

Most importantly, no one uses ArrayList anymore. It is not strongly typed, which is the reason you are getting this error.

You can:

  1. Switch to a strongly typed generic collection like List<T> which will get rid of this error among other great benefits.

  2. The downcast you are missing is needed here.

     for(int i=0;i<10;i++){ ((Bulb)bulbs[i]).printState(); }

The reason why foreach() works is because the compiler is implicitly downcasting for you given the loop variable declaration of Bulb i .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM