如何用C#反射筛选指定命名空间中的顶级类(排除被引用类)
Solution to Find Top-Level Classes in a Namespace
Here's a practical, reflection-based approach to filter out classes that are used as property types by other classes in your target namespace:
Step-by-Step Breakdown
- Grab all classes in your target namespace: First, we pull every class defined in
ConsoleApp1.Methods. - Track classes used as property types: Iterate through each class's properties, collecting any type that’s a class in the same namespace (these are the "dependent" classes).
- Filter for top-level classes: Exclude any class that appears in the tracked property types list—what’s left are your standalone top-level classes.
Complete Code Example
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public class TopLevelClassFinder { public List<Type> GetTopLevelClassesInNamespace() { // Use Assembly.Load("YourAssemblyName") if classes are in a different assembly var assembly = Assembly.GetExecutingAssembly(); const string targetNamespace = "ConsoleApp1.Methods"; // Get all classes in the target namespace var allNamespaceClasses = assembly.GetTypes() .Where(t => t.Namespace == targetNamespace && t.IsClass) .ToList(); // Collect all classes referenced as property types var usedAsPropertyTypes = new HashSet<Type>(); foreach (var cls in allNamespaceClasses) { // Adjust BindingFlags here if you need to include non-public/static properties var properties = cls.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { var propType = prop.PropertyType; // Check if the property type is a class in our target namespace if (propType.Namespace == targetNamespace && propType.IsClass) { usedAsPropertyTypes.Add(propType); } } } // Filter out dependent classes to get only top-level ones var topLevelClasses = allNamespaceClasses .Where(cls => !usedAsPropertyTypes.Contains(cls)) .ToList(); return topLevelClasses; } }
Quick Notes
- Binding Flags: If your classes use non-public properties to reference other namespace classes, update the
BindingFlags(e.g., addBindingFlags.NonPublic) to include those. - Generic Types: If you have generic property types like
List<Method100Response201_1>, this code won’t catch the generic argument. To handle that, add logic to checkpropType.GetGenericArguments()and add those types to theusedAsPropertyTypesset. - Assembly Loading: If your classes live in a separate assembly, replace
GetExecutingAssembly()withAssembly.Load("YourAssemblyName").
When you run this with your example classes, it will return exactly the top-level classes you expect: Method100Response201, Method100Response404, Method200Response200.
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

