jeudi 31 janvier 2019

Activator.CreateInstance(Type T) returns null

I want to get all classes that implements a specific interface, and show an options list so a user can choose how to implement the interface.

It is a simple interface that describes the character behavior.

I have tried to replace the Interface with an abstract class, but for no avail...

In the debug I can see, that the returned values is null.

All I have found online says that the type might not exist, but it is impossible in my case, because I get my type using reflection.

ICombatBehaviour combat;
private string[] FindAllCombatOptions(out List<Type> existingTypes)
{
    List<string> options = new List<string>();
    existingTypes = new List<Type>();
    var combatBehaviours = Assembly.GetAssembly(typeof(ICombatBehaviour)).GetTypes()
        .Where(myType => myType.IsClass && !myType.IsAbstract && typeof(ICombatBehaviour).IsAssignableFrom(myType));
    foreach (var behaviour in combatBehaviours)
    {
        existingTypes.Add(behaviour);
        options.Add(behaviour.Name);
    }
    return options.ToArray();
}
private void UpdateType(List<Type> types)
{
    combat = Activator.CreateInstance(types[index]) as ICombatBehaviour;
}

The UpdateType() method, gets all the types that FindAllCombatOptions() method has found, and takes the type in the selected index. The type is correct, but the combat variable remains null...





Aucun commentaire:

Enregistrer un commentaire