简体   繁体   中英

How to Implement Interface with Enum Specific to Derived Class in C#?

I'm trying to write an interface such as...

interface MyInterface
{
    MyObject Set(REGISTER register, PIN pin);
}

Both REGISTER and PIN are enums. The problem I'm running into is that REGISTER is defined in my MyBaseClass and PIN is defined in MyDerivedClass . I can live with using something like MyBaseClass.REGISTER in the interface, but that won't work for PIN . Every derivation of MyBaseClass will have a different enumeration for PIN . I found this other answer on SO , which seems to partially solve the problem, but it's not clear how I should then implement the function in MyDerivedClass . Does anyone have a solution for this?

Try using generics:

interface MyInterface<TPin>
{
    MyObject Set(Register register, TPin pin);
}

When you implement it in each derived class, you have to tell it what the type of the pin enum is:

class MyImplementation : MyInterface<MyPin>
{
    MyObject Set(Register register, MyPin pin)
    {
        // ...
    }
}

This means that you can't have a list of MyInterface objects, but you can have a list of MyInterface<SomePin> objects. And that makes sense - if the enum is different for each implementation, then given a MyInterface , how would you know what values to pass it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM