c# - 在 C# 中定义服务特定枚举的位置?

标签 c# interface enums namespaces

假设我有一个接口(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不同枚举。

那么有什么“最佳实践”可以解决这个问题吗?

我可以看到一些选项,但对我来说似乎没有一个是正确的:

  1. 将接口(interface)和枚举都放在特定于服务的命名空间中:

    namespace MyServices.CustomerService {
        public enum ProcessingMode { Immediate, Normal, Slow }
    
        public interface ICustomerService {
            void Process(ProcessingMode mode);
        }
    }
    

    虽然它有效并避免了包含命名空间的困惑,但它确实会导致命名空间激增,我猜服务实现可能会与命名空间冲突或重复它:MyNamespace.CustomerService.CustomerService。或者您会将服务实现放在哪里,您会怎么调用它?

  2. 仅将枚举放在单独的命名空间(或静态类)中:

    namespace MyServices {
        namespace CustomerServiceTypes {
            public enum ProcessingMode { Immediate, Normal, Slow }
        }
    
        public interface ICustomerService {
            void Process(CustomerServiceTypes.ProcessingMode mode);
        }
    }
    

    与选项 1 相同的问题,但还需要一个枚举名称才能“随处可见”。

  3. 在枚举名称前加上前缀,例如客户服务处理模式。避免 namespace 扩散和名称与服务实现冲突的风险,但会导致长而难看的枚举名称。

那么你会怎么做呢?

最佳答案

简单地将接口(interface)和枚举放在一个命名空间下。在任何情况下,您都必须使 enum public,因为您在服务内部使用它。因此通过将接口(interface)和枚举放在一个命名空间下,使得接口(interface)的实现者只包含一个命名空间。

System.DrawingColor 枚举。

关于c# - 在 C# 中定义服务特定枚举的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158592/

相关文章:

c# - 动态调整 UserControl 大小的 WPF XAML 数据绑定(bind)

c# - 无法发送电子邮件

c# - 申请表 - 检查输入是否为空

typescript - 在 Typescript 中使用 '--strictFunctionTypes' 有什么好处?

generics - 如何调用许多不同类型的函数?

.net - 我可以在 Reflector 中针对我的枚举看到的公共(public) "value__"字段的目的是什么?

c# - 循环而不卡住程序?

oop - 接口(interface)和抽象类有什么区别?

java - 在 Erlang 中使用 Dialyzer 的行为来模拟接口(interface)

c++ - 我可以传递前向声明枚举的值吗?