假设我有一个接口(interface) ICustomerService
并且这个接口(interface)需要一个枚举,例如处理模式
:
namespace MyServices {
public enum ProcessingMode { Immediate, Normal, Slow }
public interface ICustomerService {
void Process(ProcessingMode mode);
}
}
无法在 C# 的接口(interface)内部定义枚举(但显然在 VB 中?)。但是将它放在接口(interface)之外会使包含的命名空间 MyServices
变得困惑。不好,因为其他接口(interface)可能还需要一个名为 ProcessingMode
的不同枚举。
那么有什么“最佳实践”可以解决这个问题吗?
我可以看到一些选项,但对我来说似乎没有一个是正确的:
将接口(interface)和枚举都放在特定于服务的命名空间中:
namespace MyServices.CustomerService { public enum ProcessingMode { Immediate, Normal, Slow } public interface ICustomerService { void Process(ProcessingMode mode); } }
虽然它有效并避免了包含命名空间的困惑,但它确实会导致命名空间激增,我猜服务实现可能会与命名空间冲突或重复它:
MyNamespace.CustomerService.CustomerService
。或者您会将服务实现放在哪里,您会怎么调用它?仅将枚举放在单独的命名空间(或静态类)中:
namespace MyServices { namespace CustomerServiceTypes { public enum ProcessingMode { Immediate, Normal, Slow } } public interface ICustomerService { void Process(CustomerServiceTypes.ProcessingMode mode); } }
与选项 1 相同的问题,但还需要一个枚举名称才能“随处可见”。
在枚举名称前加上前缀,例如
客户服务处理模式
。避免 namespace 扩散和名称与服务实现冲突的风险,但会导致长而难看的枚举名称。
那么你会怎么做呢?
最佳答案
简单地将接口(interface)和枚举放在一个命名空间下。在任何情况下,您都必须使 enum
public
,因为您在服务内部使用它。因此通过将接口(interface)和枚举放在一个命名空间下,使得接口(interface)的实现者只包含一个命名空间。
像 System.Drawing
有 Color
枚举。
关于c# - 在 C# 中定义服务特定枚举的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158592/