mardi 19 septembre 2017

Check if PropertyInfo is interface implementation

What is the correct way to check that a given property info is an implementation of a property from an interface?

There is a class InterfaceMap that solve this problem for methods. But for properties, it provides two separate mappings for getter and setter and there still remains a problem to match those with the corresponding interface methods.

public interface IA
{
    int X { get; set; }
}

public interface IB
{
    int X { get; set; }
}

public class C : IA, IB
{
    public int X { get; set; }
    int IB.X { get; set; }
}

public PropertyInfo GetProperty<TClass, TProperty>(Expression<Func<TClass, TProperty>> getProperty)
{
    return (PropertyInfo)((MemberExpression)getProperty.Body).Member;
}

[Test]
public void Check()
{
    var aProperty = GetProperty((IA x) => x.X);
    var bProperty = GetProperty((IB x) => x.X);
    var cPropertyA = GetProperty((C x) => x.X);
    var cPropertyB = GetProperty((C x) => ((IB)x).X);

    CompareProperties(cPropertyA, aProperty); // True
    CompareProperties(cPropertyA, bProperty); // False
    CompareProperties(cPropertyB, aProperty); // False
    CompareProperties(cPropertyB, bProperty); // True
}

private bool CompareProperties(PropertyInfo classProperty, PropertyInfo interfaceProperty)
{
    // TODO implement 
}





Aucun commentaire:

Enregistrer un commentaire