确定覆盖特定方法的 类
Determine the classes that overridden a specific method
假设我有这个 class :
public class TestBase
{
public virtual bool TestMe() { }
}
我有这些 class 继承自 TestBase
Class一个
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
}
我只想 return Class A 和 B 因为它们覆盖了方法 TestMe()
,我如何通过在 Main [=35= 中创建一个方法来实现它] ?
public List<string> GetClasses(object Method)
{
// return the list of classes A and B .
}
测试类型:
- 延长
TestBase
- 声明一个
TestMe()
方法,它是:
- 虚拟
- 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()");
}
}
}
}
鉴于我们搜索由 baseType.Assembly.GetTypes()
返回的类型,这仅适用于在同一 assembly/project 中定义的子类。
要在运行时搜索所有加载的程序集,请先使用 AppDomain.CurrentDomain
枚举它们:
foreach(var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes()))
假设我有这个 class :
public class TestBase
{
public virtual bool TestMe() { }
}
我有这些 class 继承自 TestBase
Class一个
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
}
我只想 return Class A 和 B 因为它们覆盖了方法 TestMe()
,我如何通过在 Main [=35= 中创建一个方法来实现它] ?
public List<string> GetClasses(object Method)
{
// return the list of classes A and B .
}
测试类型:
- 延长
TestBase
- 声明一个
TestMe()
方法,它是:- 虚拟
- 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()");
}
}
}
}
鉴于我们搜索由 baseType.Assembly.GetTypes()
返回的类型,这仅适用于在同一 assembly/project 中定义的子类。
要在运行时搜索所有加载的程序集,请先使用 AppDomain.CurrentDomain
枚举它们:
foreach(var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes()))