Where is the best place to locate enum types?

前端 未结 10 2088
自闭症患者
自闭症患者 2020-12-25 11:16

I have found that there is generally a singe type or namespace that takes in any particular enum as a parameter and as a result I have always defined those enums there. Rece

相关标签:
10条回答
  • 2020-12-25 11:51

    Usually I find that the enum is centered around a single class -- as a MyClassOptions type of thing.

    In that case, I place the enum in the same file as MyClass, but inside the namespace but outside the class.

    namespace mynamespace
    {
      public partial class MyClass
      {
      }
      enum MyClassOptions
      {
      }
    }
    
    0 讨论(0)
  • 2020-12-25 11:55

    What environment?

    In .NET I usually create an empty class file, rename it to MyEnum or whatever to indicate it holds my enum and just declare it in there.

    0 讨论(0)
  • 2020-12-25 12:03

    Also, namespaces are for separation of things that belong together logically. Not all classes belong in the same namespace just because they are classes. Likewise, not all enums belong in the same namespace just because they are enums. Put them with the code they logically belong in.

    0 讨论(0)
  • 2020-12-25 12:06

    I tend to define them, where their use is evident in the evident. If I have a typedef for a struct that makes use of it for some reason...

    typedef enum {
      HI,
      GOODBYE
    } msg_type;
    
    typdef struct {
     msg_type type;
     union {
       int hivar;
       float goodbyevar;
      }
    } msg;
    
    0 讨论(0)
  • 2020-12-25 12:09

    I generally try to put all my different types (classes, interfaces and enums) in their own files, regardless of how small they are. It just makes it much easier to find and manage the file they're in, especially if you don't happen to be in Visual Studio and have the "go to definition" feature available. I've found that nearly every time I've put a "simple" type like that in another class, I end up either adding on to it later on, or reusing it in a way that it no longer makes sense for it to not have its own file.

    As far as which namespace, it really depends on the design of whatever you're developing. In general, I try to mimic the .NET framework's convention.

    0 讨论(0)
  • 2020-12-25 12:10

    Why treat enums differently to other types? Keep them in the same namespace as they're likely to be used - and assuming they're going to be used by other classes, make them top-level types in their own files.

    The only type of type which I do commonly clump together is delegates - I sometimes have a Delegates.cs file with a bunch of delegates in. Less so with .NET 3.5 and Func/Action, mind you.

    0 讨论(0)
提交回复
热议问题