开发者

Get Child classes from base class

Is it possible in C# to get types of subclasses f开发者_如何学运维rom base class?


You can do this:

var subclassTypes = Assembly
   .GetAssembly(typeof(BaseClass))
   .GetTypes()
   .Where(t => t.IsSubclassOf(typeof(BaseClass)));


Not directly, however you can use AppDomain.GetAssemblies() to get all the currently loaded assemblies, and then use Assembly.GetTypes() to get all the types in that assembly. Then use Type.IsSubclassOf() to determine if it's a subclass of the type you're after.


you can select the Assembly you want to check, get the types with the method Assembly.GetTypes() and test for each of them if it is a subclass with Type.IsSubclassOf()

see Assembly members and Type members


try this code:

public static IEnumerable<Type> GetAllSubclassOf(Type parent)
{
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        foreach (var t in a.GetTypes())
            if (t.IsSubclassOf(parent)) yield return t;
}


Please see the following sample code, it is similar to other codes except it is not using lambda expressions and extension methods and tested with specific class in Microsoft Visual Studio 2017 console application.

Please also see its comments, output and screenshot for more detail.

C#

// Get all the types in your assembly. For testing purpose, I am using Aspose.3D, you can use any.
var allTypes = Assembly.GetAssembly(typeof(Aspose.ThreeD.Formats.SaveOptions)).GetTypes();

foreach(var myType in allTypes)
{
    // Check if this type is subclass of your base class
    bool isSubType = myType.IsSubclassOf(typeof(Aspose.ThreeD.Formats.SaveOptions));

    // If it is sub-type, then print its name in Debug window.
    if (isSubType)
    {
        System.Diagnostics.Debug.WriteLine(myType.Name);
    }
}

Output

AMFSaveOptions
ColladaSaveOptions
Discreet3DSSaveOptions
DracoSaveOptions
FBXSaveOptions
GLTFSaveOptions
HTML5SaveOptions
ObjSaveOptions
PdfSaveOptions
PlySaveOptions
RvmSaveOptions
STLSaveOptions
U3DSaveOptions

Screenshot

Get Child classes from base class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜