C#代码规范——成员分段
这里的基本整理一般原则是:
1. 尽可能少分段
2. 关于类的尽可能靠前(例如static),关于实际对象的尽可能靠后
3. 早生成的尽可能靠前
4. 公有的,接口的尽可能靠前
5. 抽象的,通用的,基础性的,被依赖靠前;继承过来的尽量靠前
6. 相对需要引起注意的尽量靠前
7. 其他一些以往经验考虑
1 class Sample : BaseClass, IIntf1 2 { 3 #region Enumerations 4 5 enum EnumType 6 { 7 Const1, 8 // ... 9 } 10 11 #endregion 12 13 #region delegates 14 15 public void SomeEventDelegate(EventArgs e); 16 // ... 17 18 19 #endregion 20 21 #region Nested types 22 23 public class PubNestedClass 24 { 25 // ... 26 } 27 28 private class PrivNestedClass 29 { 30 } 31 32 33 #endregion 34 35 #region Fields 36 37 public static int InstanceCount = 0; 38 public int IntValue = 30; 39 40 private static int _count = 0; 41 private int _privField; 42 private const _constantField; 43 private static _staticField; 44 45 private SomeEventDelegate _eventHandlers; 46 47 48 #endregion 49 50 #region Constructors 51 52 static Sample() // static constructor first if any 53 { 54 } 55 56 public Sample(int a, int b) // constructor with the most comprehensive parameters 57 { 58 // ... 59 } 60 61 public Sample(int a) : this(a,0) 62 { 63 // ... 64 } 65 66 ~Sample() 67 { 68 } 69 70 #endregion 71 72 #region Properties 73 74 #region IIntf1 members 75 76 #region IIntf1.1 members // an interface that IIntf1 implements if any 77 78 // ... 79 80 #endregion 81 82 public int Id { get; private set; } 83 84 85 #endregion 86 87 #region BaseClass members 88 89 public new string BaseClassPropertyToOverwrite { ... } 90 91 public override string BaseClassProperty { get {...} set {...} } 92 93 #endregion 94 95 public static int Count { get; private set; } 96 public string Name { get; private set; } 97 98 private int PrivProperty { get; set; } 99 100 #endregion 101 102 #region Methods 103 104 // ... 105 106 #endregion 107 108 #region Events 109 110 public event SomeEventDelegate { add { _eventHandlers += value; } remove { ... } } 111 112 #endregion 113 114 }
// Order of execution
// 1. initialisation of fields with initialisers
// 2. static constructor
// 3. static member or object constructor
// 4. member invocation
// 5. destructor
// * nested types are instantiated when it's touched during any of the above steps and as per the same rule
enjoy every minute of an appless, googless and oracless life

浙公网安备 33010602011771号