简体   繁体   中英

How do I determine whether a method is visible outside its own assembly?

I'm trying to identify all members visible outside an assembly. My task right now is with methods. This is what I have so far:

bool isVisible = method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly;

The problem with this is that explicit interface implementations are not included by this check. How can I identify visible members including explicit interface implementations?

In general: explicitly implemented interface members are non-public, and include the interface name as part of their name.

Here is a simple code example that retrieves all of the explicitly-implemented members of an interface from a type:

private static MemberInfo[] GetExplicitInterfaceMembers(Type type)
{
    HashSet<string> interfaces = new HashSet<string>(
        type.GetInterfaces().Select(i => i.FullName.Replace('+', '.')));
    List<MemberInfo> explicitInterfaceMembers = new List<MemberInfo>();

    foreach (MemberInfo member in type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance))
    {
        int lastDot = member.Name.LastIndexOf('.');

        if (lastDot < 0)
        {
            continue;
        }

        string interfaceType = member.Name.Substring(0, lastDot);

        if (interfaces.Contains(interfaceType))
        {
            explicitInterfaceMembers.Add(member);
        }
    }

    return explicitInterfaceMembers.ToArray();
}

(Note that while nested types are given a name with + in it for the level of nesting, the type name as included in the member name of explicitly implemented interfaces has the usual . )

I assume that given the above example, you can modify the basic logic to suit your specific need.

I make no promises that the above will comprehensively identify all explicitly implemented interface members in a class for all possible interface types, but I think it will and in any case, I'm pretty sure the above will work for "normal" code (ie the only way I can think of for an exception to occur would be for some kind of odd, programmatically-generated code scenario, with which I am less familiar).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM