你可能需要的是接口映射 http://msdn.microsoft.com/en-us/library/system.reflection.interfacemapping.aspx。您可以通过调用从实际类型中获取该值GetInterfaceMap(typeof(interface))
, i.e.,
InterfaceMapping mapping = typeof(Employee).GetInterfaceMap(typeof(IEmployee));
现在,映射将包含字段InterfaceMethods
其中将包含您在反映接口时看到的方法,以及TargetMethods
这是该类的实现方法。请注意,这将接口的 getter 方法映射到目标类的 getter 方法。您需要通过将类的各种属性的 getter 方法映射到找到的 getter 方法来找到正确的接口属性。
Type interfaceType = typeof(IEmployee);
Type classType = typeof(Employee);
PropertyInfo nameProperty = interfaceType.GetProperty("Name");
MethodInfo nameGetter = nameProperty.GetGetMethod();
InterfaceMapping mapping = classType.GetInterfaceMap(interfaceType);
MethodInfo targetMethod = null;
for (int i = 0; i < mapping.InterfaceMethods.Length; i++)
{
if (mapping.InterfaceMethods[i] == nameGetter)
{
targetMethod = mapping.TargetMethods[i];
break;
}
}
PropertyInfo targetProperty = null;
foreach (PropertyInfo property in classType.GetProperties(
BindingFlags.Instance | BindingFlags.GetProperty |
BindingFlags.Public | BindingFlags.NonPublic)) // include non-public!
{
if (targetMethod == property.GetGetMethod(true)) // include non-public!
{
targetProperty = property;
break;
}
}
// targetProperty is the actual property
Caution:注意使用BindingFlags.NonPublic
and GetGetMethod(true)
在这里,用于访问私人成员。如果您有显式接口实现,则实际上并没有与接口属性匹配的公共属性,而是有一个名为的私有属性Some.NameSpace.IEmployee.Name
已映射(当然,这是您的显式实现)。
当您找到合适的房产后,您可以致电
ParameterExpression p = Expression.Parameter("e", typeof(T));
Expression<Func<T, U>> lambda = Expression.Lambda<Func<T, U>>(
Expression.Property(p, targetProperty), p);
您已经获得了一个 lambda 表达式,它使用类的属性而不是接口的属性。