Suppose that I have this class :
public class TestBase
{
public virtual bool TestMe() { }
}
and I have these classes that inherits from TestBase
Class A
public class TestA : TestBase
{
public override bool TestMe() { return false; }
}
Class B
public class TestB : TestBase
{
public override bool TestMe() { return true; }
}
Class C:
public class TestC : TestBase
{
// this will not override the method
}
I would like to return only Class A and B because they override the Method TestMe()
, How can I achieve that by creating a method in the Main class ?
public List<string> GetClasses(object Method)
{
// return the list of classes A and B .
}
CodePudding user response:
Test for types that:
- Extends
TestBase
- Declares a
TestMe()
method that's:- Virtual
- Non-abstract
var baseType = typeof(TestBase);
foreach(var type in baseType.Assembly.GetTypes())
{
if(type.IsSubclassOf(baseType))
{
var testMethod = type.GetMethod("TestMe");
if(null != testMethod && testMethod.DeclaringType == type && !testMethod.IsAbstract)
{
if(testMethod.IsVirtual)
{
// `type` overrides `TestBase.TestM()`
Console.WriteLine(type.Name " overrides TestMe()");
}
else
{
// `type` hides `TestBase.TestM()` behind a new implementation
Console.WriteLine(type.Name " hides TestMe()");
}
}
}
}
Given that we search types returned by baseType.Assembly.GetTypes()
, this only works for subclasses defined in the same assembly/project.
To search all loaded assemblies at runtime, use AppDomain.CurrentDomain
to enumerate them all first:
foreach(var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes()))