假設我有這個類:
public class TestBase
{
public virtual bool TestMe() { }
}
我有這些繼承自 TestBase 的類
A級
public class TestA : TestBase
{
public override bool TestMe() { return false; }
}
B類
public class TestB : TestBase
{
public override bool TestMe() { return true; }
}
C類:
public class TestC : TestBase
{
// this will not override the method
}
我想只回傳 A 類和 B 類,因為它們覆寫了方法TestMe(),我怎樣才能通過在 Main 類中創建方法來實作呢?
public List<string> GetClasses(object Method)
{
// return the list of classes A and B .
}
uj5u.com熱心網友回復:
測驗以下型別:
- 擴展
TestBase - 宣告一個
TestMe()方法:- 虛擬的
- 非抽象
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(),這僅適用于在同一程式集/專案中定義的子類。
要在運行時搜索所有加載的程式集,AppDomain.CurrentDomain請先使用列舉它們:
foreach(var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429026.html
上一篇:如何在C 中正確繼承抽象類?
下一篇:不要以為我得到.clone()
