Home > OS >  How to call a sub class using a string variable?
How to call a sub class using a string variable?

Time:05-29

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(itemif[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

CodePudding user response:

Looking at your code, I would like to suggest that you review the Object-Oriented Programming concept of Output of the loop

This works because the base class object has a virtual method ToString and this is why you may consider making a common base class or an interface that has the specific functionality you desire.

WORKING VERSION USING INTERFACE

static void Main(string[] args)
{
    object[] unknownObjects = new object[]
    {
        new _1001(),
        new _1002(),
        new _1003(),
    };

    // Demonstrate implicit casting to an interface
    foreach (ICommon knownInterface in unknownObjects)
    {
        knownInterface.LogData();
    }
}
interface ICommon
{
    void LogData();
}
class _1001 : ICommon
{
    public void LogData() => Console.WriteLine(GetType().Name);
}
class _1002 : ICommon
{
    public void LogData() => Console.WriteLine(GetType().Name);
}
class _1003 : ICommon    
{
    public void LogData() => Console.WriteLine(GetType().Name);
}

In doing so, you're promising the compiler that the object you're giving it in the loop will have a method called LogData.

CodePudding user response:

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;
    }
  • Related