mardi 7 février 2017

Properly finding an inherited interface property through reflection

This is a two-part question. First, which of these explicit property implementations gets bound to IAllTogether.SomeInt and why doesn't the compiler complain about ambiguity? It does when you comment-out the marked lines.

public interface IFirst
{
    int SomeInt { get; }
}

public interface ISecond
{
    int SomeInt { get; }
}

public interface ICombined : IFirst, ISecond
{
    new int SomeInt { get; } // Comment this line.
}

public interface IAllTogether : IFirst, ISecond, ICombined
{ }

public sealed class Implementation : IAllTogether
{
    int ICombined.SomeInt { get { return 0; } } // Comment this line.

    int IFirst.SomeInt { get { return 0; } }

    int ISecond.SomeInt { get { return 0; } }
}


IAllTogether t = new Implementation();
var unimportant = t.SomeInt;

Second question would be: how do I find the right PropertyInfo when given an interface Type and a name of the property? I can use FindInterfaces() and GetProperty() to list all the possible candidates, but how do I know which is the right one? I tried typeof(IAllTogether).GetProperty("SomeInt"), but it doesn't work.





Aucun commentaire:

Enregistrer un commentaire