Hui
Hui

Reputation: 57

Parsing enums to Class

The array AllUnits is a list of lists. And i am trying to add new object in to the second list. I've got also an Enumeration called EMilitaryUnits, and i have a classes with the same names as the strings in the Enumeration. And i don't know how to transform an Enumeration to Class i have tried like this

_City.Owner.Military.AllUnits[(int)_UnitType].Add(new Object.GetType(_UnitType.ToString()));

And the error is

Error 1 object.GetType() is a 'method' but is used like a type

Upvotes: 1

Views: 65

Answers (2)

Alex
Alex

Reputation: 13224

Given that:

OP has regular classes whose names correspond to the EMilitaryUnits enum value declaration names, and seeks a way to create an instance of the class corresponding to the enum name of value of _UnitType.

My recommendation would be to build a static factory to do this, as the types will be fixed and the enumeration as well. The below is an example illustrating how this could be approached.

public enum EMilitaryUnits
{
    Cavalry,
    CanonFodder,
    // ... others
};

public interface IMilitaryUnit 
{
    // rest
}

public class Cavalry : IMilitaryUnit 
{
    public Cavalry() {}
    // ... rest
}

public class CannonFodder : IMilitaryUnit 
{
    public CannonFodder() {}
    // ... rest
}

public static MilitaryUnitFactory
{
    private static readonly Dictionary<EMilitaryUnits, Func<IMilitaryUnit>> map = 
        new Dictionary<EMilitaryUnits, Func<IMilitaryUnit>> {
            { EMilitaryUnits.Cavalry, () => new Cavalry() },
            { EMilitaryUnits.CanonFodder, () => new CanonFodder() },
            // more for the others
        };

    public static IMilitaryUnit Create(EMilitaryUnits kind)
    {
        return map[kind]();
    }
}

Usage example:

_City.Owner.Military.AllUnits[(int)_UnitType].Add(MilitaryUnitFactory.Create(_UnitType));

Upvotes: 1

Nikolay
Nikolay

Reputation: 12235

Instead of this part:

new Object.GetType(_UnitType.ToString())

Try this (substiture with the namespace where your types are defined):

Activator.CreateInstance(Type.GetType("<namespace>." + _UnitType.ToString()))

Upvotes: 1

Related Questions