如何识别派生类并通过反射从基类启动其成员

时间:2016-07-22 09:00:19

标签: c# reflection derived-class base-class

我有一个基类:

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

    public eGuiType GuiType;
}

然后我有各种派生类,其中一个是这个

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(){...}
}

所以现在在启动我的应用程序时,我使用了该代码:

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();

}

最后我用

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

所以我需要做的是[伪代码放在哪里???是

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

然后

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

所以总之我必须:

  1. 识别实例类型throgh eIoType

  2. 如果ioType == MONITOR执行其Action例程

  3. 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

if (classType.Name == "ClassIO")
{
    //You can get the field like this
    var fieldInfo = classType.GetField("ioType",BindingFlags.NonPublic|BindingFlags.Instance);
    if (fieldInfo != null)
    {
        //...
    }

    //You can get the method like this
    var methodInfo = classType.GetMethod("Action");
    if (methodInfo != null)
    {
        //create an instance of ClassIO
        var classInstance = Activator.CreateInstance(classType, new eGuiType(), ClassIO.eIoType.MONITOR);
        //Execute Action method
        methodInfo.Invoke(classInstance, null);
    }
}

我不确定您认为自己如何检查eIoType的价值,但您只是在这里处理类型 ClassIO不是它的一个实例