C# 检查PropertyInfo是否为接口实现

C# 检查PropertyInfo是否为接口实现,c#,reflection,C#,Reflection,检查给定属性信息是否是接口属性实现的正确方法是什么 有一个类InterfaceMap可以解决方法的这个问题。但对于属性,它为getter和setter提供了两个单独的映射,并且仍然存在将这些映射与相应的接口方法相匹配的问题 公共接口IA { int X{get;set;} } 公共接口IB { int X{get;set;} } 公共C类:IA、IB { 公共整数X{get;set;} int IB.X{get;set;} } 公共属性信息GetProperty(表达式GetProperty)

检查给定属性信息是否是接口属性实现的正确方法是什么

有一个类
InterfaceMap
可以解决方法的这个问题。但对于属性,它为getter和setter提供了两个单独的映射,并且仍然存在将这些映射与相应的接口方法相匹配的问题

公共接口IA
{
int X{get;set;}
}
公共接口IB
{
int X{get;set;}
}
公共C类:IA、IB
{
公共整数X{get;set;}
int IB.X{get;set;}
}
公共属性信息GetProperty(表达式GetProperty)
{
返回(PropertyInfo)((MemberExpression)getProperty.Body.Member;
}
[测试]
公共作废检查()
{
var aProperty=GetProperty((IA x)=>x.x);
var bProperty=GetProperty((IB x)=>x.x);
var cPropertyA=GetProperty((cx)=>x.x);
var cPropertyB=GetProperty((cx)=>((IB)x).x);
比较属性(cPropertyA,aProperty);//True
比较属性(cPropertyA、bProperty);//False
比较属性(cPropertyB,aProperty);//False
比较属性(cPropertyB,bProperty);//True
}
私有布尔比较属性(PropertyInfo类属性、PropertyInfo接口属性)
{
//待办事项实施
}
对于给定的,您可以使用和属性分别访问getter和setter的

因此,应该可以用一个小助手的方法来比较:

private static bool MethodsImplements(InterfaceMap interfaceMap,
    MethodInfo interfaceMethod, MethodInfo classMethod)
{
    var implIndex = Array.IndexOf(interfaceMap.InterfaceMethods, interfaceMethod);
    return interfaceMethod == interfaceMap.TargetMethods[implIndex];
}
然后,可以按如下方式使用该方法来实现您所需的方法:

var interfaceType = interfaceProperty.DeclaringType;
var interfaceMap = classProperty.DeclaringType.GetInterfaceMap(interfaceType);

var gettersMatch = classProperty.CanRead && interfaceProperty.CanRead
    && MethodImplements(interfaceMap, interfaceProperty.GetMethod, classProperty.GetMethod);

var settersMatch = classProperty.CanWrite && interfaceProperty.CanWrite
    && MethodImplements(interfaceMap, interfaceProperty.SetMethod, classProperty.SetMethod);

那么,返回<代码> GETTSES匹配>匹配器,因为接口属性可能只有一个吸收器或者只有一个SETER。只需要getter的接口可能由同时具有getter和setter的公共属性实现。问题是,将getter用于class属性和getter用于接口属性无法正确比较它们是否相等。对

Equals
的简单调用返回
false
,因为它们具有不同的声明类型。@Damien\u不相信者即使接口属性只指定了一个getter,并且类实现同时具有getter和setter,问题仍然存在:如何检查此特定属性是否实现了该接口。