简体   繁体   English

接口不能声明类型

[英]Interfaces cannot declare types

I have an abstract class in an API that is used by methods in another assembly.我在另一个程序集中的方法使用的 API 中有一个抽象类。 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.然后我决定如果 Thing 是一个界面会是一个更好的设计。 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.但是,如果我将枚举的定义移到接口之外,首先我会破坏封装(Status 类型确实属于 Thing 并且本身没有意义),更重要的是我必须去修改代码许多其他使用它的程序集。 Can you think of any solutions?你能想到什么解决办法吗?

As the error indicates, you just have to pull the definition of Status outside of the interface.如错误所示,您只需将Status的定义拉到界面之外。 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.我建议您将Status的名称更改为表明与Thing ThingStatus应该可以解决问题。

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).如果您坚持使用接口,恐怕您必须采用pswg 的解决方案并违反一两条规则(无论如何,这些只是指导方针,真的)。

abstract class and interface are different things. abstract类和interface是不同的东西。 abstarct class is abstraction, higher than your domain model and interface is the contract (behavior) of your domain entity. abstarct类是抽象的,高于你的领域模型,接口是你领域实体的契约(行为)。 You can use both in your solution as necessary.您可以根据需要在解决方案中同时使用两者。 In concrete scenario status is not behavior it just state of entity.在具体场景中, status不是行为,它只是实体的状态。 I think abstract class is more reliable choice.我认为抽象类是更可靠的选择。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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