How to iterate only over properties that don't belong to base class

Viewed 50

I have the following generic class:

public class TestGenericRenderer<TXamarinView, TNativeView>
    : ViewRenderer<TXamarinView, TNativeView>

    where TXamarinView : Xamarin.Forms.VisualElement
    where TNativeView : System.Windows.FrameworkElement
{
    protected override void OnElementChanged(ElementChangedEventArgs<TXamarinView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            var xamarinType = e.NewElement.GetType();
            var nativeView = Activator.CreateInstance(typeof(TNativeView));
            var nativeProps = nativeView.GetType().GetProperties();
            foreach (var prop in xamarinType.GetProperties())
            {
                var corrProp = nativeProps.FirstOrDefault(x => x.Name == prop.Name);
                if (corrProp != null)
                {
                    try
                    {
                        corrProp.SetValue(nativeView, prop.GetValue(e.NewElement));
                    }
                    catch { }
                }
            }
            ...

When iterating through the properties of xamarinType, I want to only get the properties that weren't declared in classes it inherits, otherwise there will be type mismatches (and therefore it only works thanks to the try-catch hack)

How can I skip these properties?

1 Answers

Use the BindingFlags.DeclaredOnly flag to get only properties declared by the target type:

xamarinType.GetProperties(
    BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
Related