How to call a sub class using a string variable?

186 views Asked by At

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

2

There are 2 answers

0
IV. On

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.

interface ICommon
{
    void LogData();
}
class _1001 : ICommon
{
    public void LogData() => 
        Console.WriteLine("Class-specific datalogging for 'class _1001'.");
}
class _1002 : ICommon
{
    public void LogData() => 
        Console.WriteLine("Class-specific datalogging for 'class _1002'.");
}
class _1003 : ICommon    
{
    public void LogData() => 
        Console.WriteLine("Class-specific datalogging for 'class _1003'.");
}

Each of these classes will implement the ICommon and in particular the LogData method in its own class-specific way. This holds even if we instantiate them as type object:

    object[] unknownObjects = new object[]
    {
        new _1001(),
        new _1002(),
        new _1003(),
    };

The interface allows for implicit casting when looping the object[]

    // Demonstrate implicit casting to an interface
    foreach (ICommon knownInterface in unknownObjects)
    {
        knownInterface.LogData();
    }
}

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 implement ICommon you would get an InvalidCastException at runtime.

The output of the loop is:

enter image description here

0
jegan24 On

I don't recommend doing this, but if you don't want to create an interface like IVSoftware recommended, this function should do what you want.

    static object AccessPropertyWithReflections(object obj, string propertyName)
    {
        object output = null;
        var typeInfo = obj.GetType();
        var propertyInfo = typeInfo.GetProperty(propertyName);
        if (propertyInfo is not null)
        {
            output = propertyInfo.GetValue(obj);
        }
        return output;
    }