What's the best way to layout a C# class? [dup

2019-01-30 00:20发布

This question already has an answer here:

Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?

Here's what I normally do, but I'm wondering if there's a standard way?

  1. Nested Classes or Enums
  2. Fields
  3. Properties
  4. Events
  5. Constructors
  6. Public Methods
  7. Private Methods

Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.

Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.

10条回答
再贱就再见
2楼-- · 2019-01-30 00:39

Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.

Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.

查看更多
成全新的幸福
3楼-- · 2019-01-30 00:45

You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.

查看更多
聊天终结者
4楼-- · 2019-01-30 00:49

I tend to clump private data and tend to clump related methods/properties in functional groups.

public class Whatever {
   // private data here
   int _someVal = kSomeConstant;

   // constructor(s)
   public Whatever() { }

#region FabulousTrick  // sometimes regionize it
   // fabulous trick code
   private int SupportMethodOne() { }
   private double SupportMethodTwo() { }
   public void PerformFabulousTrick(Dog spot) {
       int herrings = SupportMethodOne();
       double pieces = SupportMethodTwo();
       // etc
   }
#endregion FabulousTrick
   // etc
}
查看更多
Ridiculous、
5楼-- · 2019-01-30 00:50

I use the following layout:

events globals/class-wide fields private/internal properties methods public/protected properties methods nested classes (although I try to avoid these whenever possible)

I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.

查看更多
登录 后发表回答