Method overload: calling a sequence to overload class arguments

Ok, I'm trying to do the following:

        protected bool ValidAdvert(Base item)
        {
            throw ThisIsAnAbstractClassException();
        }

        protected bool ValidAdvert(Derived1 item)
        {
            return ADerived1SpecificPredicate;
        }

        protected bool ValidAdvert(Derived2 item)
        {
            return ADerived2SpecificPredicate;
        }    

And the version of the Derived class of the method must be called when the base class is passed to the method. The base class is abstract, so is this theoretically possible?

Before someone says something about method overloading on the classes themselves, the logic inside the methods relies on a large number of different conditions, none of which are related, and none of them are directly related to the base / derived class (for example, how login status, etc.)

+5
source share
3 answers

, , .

protected bool ValidAdvert(Base item)
{
    if (item.GetType() == typeof(Base))
        throw new ThisIsAnAbstractClassException();

    Type type = typeof(CurrentClass);

    MethodInfo method = type.GetMethod("ValidAdvert",
                                       BindingFlags.Instance | BindingFlags.NonPublic,
                                       null,
                                       new Type[] { item.GetType() },
                                       null);
    return (bool)method.Invoke(this, new object[] { item });
}

protected bool ValidAdvert(Derived1 item)
{
    return ADerived1SpecificPredicate;
}

protected bool ValidAdvert(Derived2 item)
{
    return ADerived2SpecificPredicate;
}

MultipleDispatch, , ( ), , Double Dispatch.

, # 4.0 dynamic:

protected bool ValidAdvert(Base item)
{
    if (item.GetType() == typeof(Base))
        throw new ThisIsAnAbstractClassException();

    dynamic dynamicThis = this;

    return (bool)dynamicThis.ValidAdvert(item as dynamic);
}
+6

:

class Base
{
    public abstract bool IsValid(IAdvertValidator validator);
}

class Derived1 : Base
{
    public bool IsValid(IAdvertValidator validator)
    {
        return validator.ValidAdvert(this);
    }
}

class Derived2 : Base
{
    public bool IsValid(IAdvertValidator validator)
    {
        return validator.ValidAdvert(this);
    }
}

interface IAdvertValidator
{
    bool ValidAdvert(Derived1 d1);
    bool ValidAdvert(Derived2 d2);
}
+5

I don’t know exactly how you will have an instance of a base class that is not really an instance of a derived class. Since the base class is abstract, it cannot be created. I guess this would match any derived class that doesn't have a specific signature, but that doesn't seem to be what you are going to do.

0
source

All Articles