如何确定一个方法在它自己的程序集之外是否可见?
How do I determine whether a method is visible outside its own assembly?
我正在尝试识别在程序集外可见的所有成员。我现在的任务是方法。这是我目前所拥有的:
bool isVisible = method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly;
问题在于此检查不包括显式接口实现。如何识别可见成员,包括显式接口实现?
通常:显式实现的接口成员是非public,并将接口名称作为其名称的一部分。
这是一个简单的代码示例,它从类型中检索接口的所有显式实现的成员:
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();
}
(请注意,虽然嵌套类型的名称中包含 +
以表示嵌套级别,但显式实现接口的成员名称中包含的类型名称具有通常的 .
)
我假设给出上面的示例,您可以修改基本逻辑以满足您的特定需要。
我不保证上面的内容会在 class 中针对所有可能的接口类型全面识别所有显式实现的接口成员,但我 认为 它会并且在无论如何,我很确定上面的代码适用于 "normal" 代码(即我能想到的发生异常的唯一方法是针对某种奇怪的、以编程方式生成的代码场景,我用它不太熟悉)。
我正在尝试识别在程序集外可见的所有成员。我现在的任务是方法。这是我目前所拥有的:
bool isVisible = method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly;
问题在于此检查不包括显式接口实现。如何识别可见成员,包括显式接口实现?
通常:显式实现的接口成员是非public,并将接口名称作为其名称的一部分。
这是一个简单的代码示例,它从类型中检索接口的所有显式实现的成员:
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();
}
(请注意,虽然嵌套类型的名称中包含 +
以表示嵌套级别,但显式实现接口的成员名称中包含的类型名称具有通常的 .
)
我假设给出上面的示例,您可以修改基本逻辑以满足您的特定需要。
我不保证上面的内容会在 class 中针对所有可能的接口类型全面识别所有显式实现的接口成员,但我 认为 它会并且在无论如何,我很确定上面的代码适用于 "normal" 代码(即我能想到的发生异常的唯一方法是针对某种奇怪的、以编程方式生成的代码场景,我用它不太熟悉)。