简体   繁体   中英

Interfaces cannot declare types

I have an abstract class in an API that is used by methods in another assembly. The class has a nested enum defined inside it, a bit like this:

abstract public class Thing
{
    public enum Status { Accepted, Denied, Pending };
    abstract public Status status { get; private set; }
    etc...
}

I then decided it would be a better design if Thing was an interface. But I can't do this:

public interface Thing
{
    enum Status { Accepted, Denied, Pending };
    Status status { get; }
    etc...
}

This produces the error message "Interfaces cannot declare types." However, if I move the definition of the enum outside of the interface, firstly I'd be breaking encapsulation (the Status type really belongs to Thing and is meaningless on its own) and more importantly I would have to go and modify the code in the many other assemblies that use this. Can you think of any solutions?

As the error indicates, you just have to pull the definition of Status outside of the interface. I understand that it breaks encapsulation, but there's really no way around this. I suggest you change the name of Status to something which indicates a strong relation to Thing -- ThingStatus should do the trick.

enum ThingStatus { Accepted, Denied, Pending };

public interface Thing
{
    ThingStatus status { get; }
    etc...
}

Oh yes, the solution is to use an abstract class if you need such implementation. Abstract classes are not a bad design and are certainly useful in situations like this.

If you insist on using interfaces, I'm afraid you'd have to go with the solution from pswg and break a rule or two (those are just guidelines anyway, really).

abstract class and interface are different things. abstarct class is abstraction, higher than your domain model and interface is the contract (behavior) of your domain entity. You can use both in your solution as necessary. In concrete scenario status is not behavior it just state of entity. I think abstract class is more reliable choice.

您必须在命名空间内或命名空间外将类型声明为公共类型,然后在接口中声明该类型的方法

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