Method overload

When I call EntryPoint with a parameter of type TemplateA, I always get an exception, because the first overload is always called.
What I expected was that the most specific method (second overload) would be called due to dynamic binding.
Any ideas why?

private object _obj;
    public void EntryPoint(object p)
    {
        myFunc(p);
    }

    //first overload
    private void myFunc(object container)
    {
        throw new NotImplementedException();
    }

    //second overload
    private void myFunc(TemplateA template)
    {
        _obj = new ObjTypeA(template);
    }

    //third overload
    private void myFunc(TemplateB template)
    {
        _obj = new ObjTypeB(template);
    }
+3
source share
4 answers

You can do this in C # 4.0 if you use dynamicinstead object. Download the beta version of Visual Studio 2010 if you want to try it. Up to this point, the compiler selects exactly which method to call based on the compilation types of the parameters.

, , .

class TemplateBase
{
    public virtual object MyFunc()
    {
        throw new NotImplementedException();
    }
}

class TemplateA : TemplateBase
{
    public override object MyFunc()
    {
        return new ObjTypeA(this);
    }
}

class TemplateB : TemplateBase
{
    public override object MyFunc()
    {
        return new ObjTypeB(this);
    }
}

:

private object _obj;

public void EntryPoint(TemplateBase p)
{
    _obj = p.MyFunc();
}

, TemplateN. EntryPoint Dictionary Type .

Dictionary<Type, Func<object, object>> _myFuncs;

_myFuncs.Add(typeof(TemplateA), o => new ObjTypeA((TemplateA)o));
_myFuncs.Add(typeof(TemplateB), o => new ObjTypeB((TemplateA)o));

.

Func<object, object> f = _myFuncs[p.GetType()];
_obj = f(p);

, .

+1

, , - ( ).

? object. , . .

: , .

+4

EntryPoint() TemplateA, object. , myFunc(p) object.

+2

, EntryPoint , ,

0
source

Source: https://habr.com/ru/post/1713564/


All Articles