mercredi 2 août 2023

Text existence of covariant property without generating AmbiguousMatchException

My base view model uses Type.GetProperty to verify that a given property (for which we are about to raise PropertyChanged) actually exists in the class.

It works great. But if you test for the existence of a property that you have overridden with a more derived type (ie.a covariant return types), an AmbiguousMatchException is generated. I can catch and avoid this but I would like to silence it. It makes my debugging experience more noisy.

Is there an alternate or more-specific way to test for the existence of such a property and NOT get an AmbiguousMatchException?

Here is an oversimplified version of the base view model.

public abstract class Observable  : INotifyPropertyChanged
{
    protected void RaisePropertyChanged(string propertyName)
    {
        try
        {
            if (null == type.GetProperty(propertyName)
                 Debug.Fail($"{propertyName} is not a public property of {type.FullName}");
            else
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        catch(AmbiguousMatchException)
        {
        }
    }
}

And here are some classes (deliberately stripped-down) that use covariant return types to on a property.

When I check for the existence of the "Geometry" property in the base class, I get the exception

public abstract class Shape  : Observable { public abstract Geometry        Geometry { get; } }
public          class Circle : Shape      { public          EllipseGeometry Geometry { get; } }
public          class Line   : Shape      { public          LineGeometry    Geometry { get; } } 




Aucun commentaire:

Enregistrer un commentaire