So I have this simple for loop and I want to access a variable of a class
However there are multiple classes so that's how I ended up with for loop.
This is what my code looks like.
for (int i = 0; i<itemId.Length; i++)
{
Type type = Type.GetType(" " + itemid[i]);
object instance = Activator.CreateInstance(type);
Debug.Log(itemResponse.data.Invoke(itemid[i]).name);
}
I am trying to access
itemResponse.data."My String".name
The classes I want to access are.
public class _1001{ }
public class _1002{ }
public class _1003{ }
and so on, is there any way I could do that?
Thanks
The Object-Oriented Programming concept of Polymorphism can simplify solving your question. It's what's "under the hood" for the very excellent comment about implementing an interface.
Here's the most basic demo I can think of. I've made the three classes that you name in your post, but in addition have defined a common interface.
Each of these classes will implement the
ICommon
and in particular theLogData
method in its own class-specific way. This holds even if we instantiate them as typeobject
:The interface allows for implicit casting when looping the
object[]
Basically, you're promising the compiler that the object you're giving it in the loop will have a method called
LogData
. It then proceeds to call the correct class-specific implementation without a lot of fuss and bother. And if you were to attempt it with an object that doesn't implementICommon
you would get anInvalidCastException
at runtime.The output of the loop is: