vendredi 22 juillet 2016

How to identify a derived class and launch its member from the base class through reflection

I have a base class:

abstract class ClassPlugin
{   
    public ClassPlugin(eGuiType _guyType)
    {
        GuiType = _guyType;
    }

    public eGuiType GuiType;
}

then I have various derived classes, one of them being this

class ClassIO : ClassPlugin
{
    public ClassIO(eGuiType _guyType, eIoType _ioType) : base(_guyType)
    {
        GuyType = _guyType;
        ioType = _ioType;
    }

    eIoType ioType; 
    public enum eIoType { UKNOWN, READ, WRITE, MONITOR }
    public override void Action(){...}
}

so now when launching my application I use that code:

public static List<Type> FindAllDerivedTypes<T>()
{
    return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
}

public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)
{
    var derivedType = typeof(T);
    return assembly
            .GetTypes()
            .Where(t =>
                    t != derivedType && derivedType.IsAssignableFrom(t)).ToList();

}

finally I use it with

var output = FindAllDerivedTypes<ClassPlugin>();
foreach (var classType in output)
{
    if (classType.Name == "ClassIO")
    {
        foreach (var item in classType.GetMembers())
        {
            ????        
        }
    }
}

so what I need to do is [pseudocode to be put where the ??? are]

bool IsMonitorType = false;
if(item.member == eIoType && item.Value == eIoType.MONITOR)
{
    IsMonitorType == true;
    break;
}

and then

if(item.member.Name "Action")
{
    item.member.execute();
}

so in short I have to:

  1. identify the instance type throgh eIoType

  2. if ioType == MONITOR execute its Action routine

Thank you for any help





Aucun commentaire:

Enregistrer un commentaire