문제

Okay, the title may sound a bit confusing, just read my explanation here to understand what I mean:

I got a base class, lets call it BaseProvider. This class looks like this:

public abstract class BaseProvider
{
    public abstract void NewItem(int type);
}

Now I add a second class that derives from the BaseProvider. Lets call it TestProvider:

public class TestProvider : BaseProvider
{
    public override void NewItem(int type)
    {

    }
}


Okay, now here comes my question / problem:

As there are different sub-types that this provider should be able to handle, I created the parameter int type. However it would be much nicer to be able to use Enums. And as every data provider will have a different set of sub-types I can't reuse a already existing one. Now my method signature has to match exactly the one from the base class which makes it impossible to change the parameter type to an enum (even though an enum is basically an int).

I did try to define my deriving class like the following:

public class TestProvider : BaseProvider
{
    public override void NewItem(MyEnum type)
    {

    }
}

enum MyEnum : int
{
    TEST = 1
}

As excpeted this does not work...
So my question now is:

Is it possible to overwrite a base function with a different parameter type that derives from the parameter type defined in the base class? If yes how?

도움이 되었습니까?

해결책

No, absolutely not - and here's why... This code still has to work:

BaseProvider provider = new TestProvider();
provider.NewItem(10);

That's just the normal requirements of polymorphism. You can't change a signature when you're overriding, because callers may be considering your instance in terms of the base class instead. (Indeed, if they're not doing so, why bother having the abstract method at all?)

Now you can overload the method:

public override void NewItem(int type)
{
    NewItem((MyEnum) type);
}

public void NewItem(MyEnum type)
{
    ...
}

That's not quite the same thing, but it probably achieves what you want.

Alternatively, you could make BaseProvider generic:

public abstract class BaseProvider<T>
{
    public abstract void NewItem(T type);
}

public class TestProvider : BaseProvider<MyEnum>
{
    public override void NewItem(MyEnum type)
    {
    }
}

다른 팁

You are actually missing out the concept of overriding here. It is not about changing method definition. It is about changing method behavior. What you could do here is either overload, or make sure you cast your enum as int before call.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top