jeudi 21 février 2019

Replacing casting with reflection to check if object has a given property

Basically what I would like to achieve is to replace this:

interface IHasName
{
    string Name {get;}
}

void Check(object item)
{
    if (item is IHasName namedItem)
    {
        checkName(namedItem.Name);
    }
}

by this:

void Check(object item)
{
    if (GetNameProperty(item) is string nameValue)
    {
        checkName(nameValue);
    }
}

Then there would be no need for the IHasName interface, which I believe would make my code more simple and thus better. (although to be honest I am not sure if this is the best way to go, so advice is welcome)





Aucun commentaire:

Enregistrer un commentaire