Is the #region directive really useful in .NET?

后端 未结 17 2077
孤城傲影
孤城傲影 2021-01-03 23:43

After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of \"make work\" for the programmer. It\'s w

17条回答
  •  情书的邮戳
    2021-01-04 00:20

    I don't generally use code regions, except in one specific case - dependency properties. Although dependecy properties are a pleasure to work with in most respects, their declaraions are an eyesore and they quickly clutter your code. (As if managing GUI code was not already enough of a challenge...)

    I like to give the region the same exact name as the CLR property declaration (copy/paste it in there). That way you can see the scope, type and name when it's collapsed - which is really all you care about 95% of the time.

       #region public int ObjectDepthThreshold
    
        public int ObjectDepthThreshold
        {
            get { return (int)GetValue(ObjectDepthThresholdProperty); }
            set { SetValue(ObjectDepthThresholdProperty, value); }
        }
    
        public static readonly DependencyProperty ObjectDepthThresholdProperty = DependencyProperty.Register(
            "ObjectDepthThreshold",
            typeof(int),
            typeof(GotoXControls),
            new FrameworkPropertyMetadata((int)GotoXServiceState.OBJECT_DEPTH_THRESHOLD_DEFAULT,
                FrameworkPropertyMetadataOptions.AffectsRender,
                new PropertyChangedCallback(OnControlValueChanged)
            )
        );
    
        #endregion
    

    When it's collapsed you just see

    public int ObjectDepthThreshold
    

    If I have more than one dependency property, I like to start the next #region on the very next line. That way you end up with all of them grouped together in your class, and the code is compact and readable.

    BTW if you just want to peek at the declaration, mouse hover over it.

提交回复
热议问题