lundi 8 août 2022

C# Get internal, but not private or protected methods of a type [duplicate]

I am trying to get some statistics about our C# library and how many internal methods we have. I have tried using System.Reflection for it, but I am struggling with filtering just internal methods and not private or protected ones. Here is my code:

private bool IsTypePublic(Type t)
{
    return
        t.IsVisible
        && t.IsPublic
        && !t.IsNotPublic
        && !t.IsNested
        && !t.IsNestedPublic
        && !t.IsNestedFamily
        && !t.IsNestedPrivate
        && !t.IsNestedAssembly
        && !t.IsNestedFamORAssem
        && !t.IsNestedFamANDAssem;
}

private bool IsTypeInternal(Type t)
{
    return
        !t.IsVisible
        && !t.IsPublic
        && t.IsNotPublic
        && !t.IsNested
        && !t.IsNestedPublic
        && !t.IsNestedFamily
        && !t.IsNestedPrivate
        && !t.IsNestedAssembly
        && !t.IsNestedFamORAssem
        && !t.IsNestedFamANDAssem;
}

private Dictionary<string, int> GetMethodCounts()
{
    var assembly = typeof(MyType).Assembly;
    var types = assembly.GetTypes();

    var result = new Dictionary<string, int>();
    var publicTypes = new HashSet<Type>();
    var internalTypes = new HashSet<Type>();

    foreach (var type in types)
    {
        if (IsTypePublic(type))
        {
            publicTypes.Add(type);
        }
        else if (IsTypeInternal(type))
        {
            internalTypes.Add(type);
        }
    }

    result.Add("PublicType.PublicMethod", 
        // Select all non-inherited public methods, both static and instance-bound
        publicTypes.SelectMany(x => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly))
            .Count(x => !x.IsSpecialName));

    result.Add("PublicType.InternalMethod",
        // This should select all non-inherited internal methods, both static and instance-bound
        // But it selects also private and protected methods, which I am not interested in
        publicTypes.SelectMany(x => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
            .Count(x => !x.IsSpecialName));

    // ... continue with constructors, properties, and the same for the internalTypes
}

Is there any way how to limit the scope to internal only (or possibly protected internal)?





Aucun commentaire:

Enregistrer un commentaire