Iva*_*vov 13 .net c# reflection explicit-interface
我需要能够确定给定的方法或属性是否来自特定接口并且是否明确实现.
有没有人这样做,是否有可能通过.NET反射获取此信息?
更新
从下面的评论中可以看出接受的答案,我想要实现的实际事情是通过反射调用实现特定接口的方法.由于可能有多个具有相同方法签名的接口,我想确定基于接口调用的正确实现.在我的场景中,实现类型,接口和方法名称是在运行时确定的,所以我不能在我的情况下使用简单的转换.
Jor*_*dão 16
C#中明确实现的接口方法在目标类中是私有的.您可以使用此事实并创建此扩展方法以仅返回以下方法:
static IEnumerable<MethodInfo> GetExplicitlyImplementedMethods(this Type targetType,
Type interfaceType)
{
return targetType.GetInterfaceMap(interfaceType).TargetMethods.Where(m => m.IsPrivate);
}
Run Code Online (Sandbox Code Playgroud)
注:这是C#只.
更新:但是,根据您的要求,您似乎只想知道哪些方法实现了哪些接口方法,而没有真正关心实现是隐式的还是显式的.对于跨语言的解决方案,这就足够了:
static IEnumerable<MethodInfo> GetImplementedMethods(this Type targetType,
Type interfaceType)
{
return targetType.GetInterfaceMap(interfaceType).TargetMethods;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2246 次 |
| 最近记录: |