获取没有从给定接口派生的类属性

时间:2014-01-28 07:46:28

标签: c# reflection

是否有一种干净的方法来查询属性的类型并过滤来自界面的那些?

假设我有一个类和一个接口

public interface IFoo 
{
    string Bar { get; set; }
}

public class Foo : IFoo 
{
    public string Bar { get; set; }
    public string Baz { get; set; }
}

我希望得到一个仅包含PropertyInfo属性的Baz数组。

编辑:

这就是我现在所拥有的......我知道它并不完美,但它确实有用。

var allProperties = typeof(T).GetProperties();
var interfaceMethods = typeof(T).GetInterfaceMap(typeof(IFoo)).TargetMethods;
return allProperties.Where(x => !interfaceMethods.Contains(x.GetGetMethod()) || !interfaceMethods.Contains(x.GetSetMethod())).ToArray();

2 个答案:

答案 0 :(得分:1)

您希望使用InterfaceMapping

    private static bool IsInterfaceImplementation(PropertyInfo p, InterfaceMapping interfaceMap)
    {
        var getterIndex = Array.IndexOf(interfaceMap.TargetMethods, p.GetGetMethod());
        var setterIndex = Array.IndexOf(interfaceMap.TargetMethods, p.GetSetMethod());

        return getterIndex != -1 || setterIndex != -1;
    }

    private static PropertyInfo[] GetPropertiesExcludeInterfaceImplementation(Type type, Type interfaceType)
    {
        var interfaceMap = type.GetInterfaceMap(interfaceType);

        return type
            .GetProperties()
            .Where(p => !IsInterfaceImplementation(p, interfaceMap))
            .ToArray();
    }

答案 1 :(得分:0)

您可以加载类实现的所有接口,并获取这些接口的所有属性。获取类的属性时,可以检查属性是否已由其中一个接口定义:

var interfaceProperties = typeof(Foo)
   .GetInterfaces()
   .SelectMany( i => i.GetProperties() )
   .ToList();

var properties = typeof(Foo)
   .GetProperties()
   .Where(p => !interfaceProperties.Any( ip => ip.Name==p.Name && ip.PropertyType==p.PropertyType) );