【问题标题】:C# 3.0 Auto-Properties - Is it possible to add custom behaviour?C# 3.0 Auto-Properties - 是否可以添加自定义行为?
【发布时间】:2010-09-12 01:58:52
【问题描述】:

我想知道是否有任何方法可以将自定义行为添加到自动属性 ​​get/set 方法中。

我能想到的一个明显案例是希望每个 set 属性方法都调用任何 PropertyChanged 事件处理程序,作为 System.ComponentModel.INotifyPropertyChanged 实现的一部分。这将允许一个类具有许多可以观察到的属性,其中每个属性都使用自动属性语法定义。

基本上我想知道是否有任何类似于 get/set 模板或 post get/set hook 的类范围。

(我知道相同的最终功能可以通过稍微冗长的方式轻松实现 - 我只是讨厌重复模式)

【问题讨论】:

    标签: c# .net properties automatic-properties


    【解决方案1】:

    不,您必须对自定义行为使用“传统”属性定义。

    【讨论】:

      【解决方案2】:

      不,你不能:自动属性是显式访问私有字段的快捷方式。例如

      public string Name { get; set;} 
      

      是一个快捷方式

      private string _name;
      public string Name { get { return _name; } set { _name = value; } };
      

      如果要放置自定义逻辑,则必须显式编写 get 和 set。

      【讨论】:

        【解决方案3】:

        查看PostSharp。它是一个 AOP 框架,用于典型的问题“这个代码模式我一天做几百次,我怎样才能自动化它?”。 您可以使用 PostSharp 简化这个(例如):

        public Class1 DoSomething( Class2 first, string text, decimal number ) {
            if ( null == first ) { throw new ArgumentNullException( "first" ); }
            if ( string.IsNullOrEmpty( text ) ) { throw new ArgumentException( "Must be not null and longer than 0.", "text" ) ; }
            if ( number < 15.7m || number > 76.57m ) { throw new OutOfRangeArgumentException( "Minimum is 15.7 and maximum 76.57.", "number"); }
        
            return new Class1( first.GetSomething( text ), number + text.Lenght );
        }
        

            public Class1 DoSomething( [NotNull]Class2 first, [NotNullOrEmpty]string text, [InRange( 15.7, 76.57 )]decimal number ) {
                return new Class1( first.GetSomething( text ), number + text.Lenght );
        }
        

        但这还不是全部! :)

        【讨论】:

          【解决方案4】:

          如果这是您在开发过程中经常重复的行为,您可以为您的特殊类型的属性创建自定义代码 sn-p。

          【讨论】:

            【解决方案5】:

            您可以考虑使用PostSharp 编写setter 拦截器。它既是 LGPL 又是 GPL 取决于您使用的库的哪些部分。

            【讨论】:

              【解决方案6】:

              我能想到的最接近的解决方案是使用辅助方法:

              public void SetProperty<T>(string propertyName, ref T field, T value)
               { field = value;
                 NotifyPropertyChanged(propertyName);
               }
              
              public Foo MyProperty 
               { get { return _myProperty}
                 set { SetProperty("MyProperty",ref _myProperty, value);}
               } Foo _myProperty;
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-09-30
                • 1970-01-01
                • 1970-01-01
                • 2012-05-05
                • 2019-10-22
                • 2019-11-10
                • 1970-01-01
                相关资源
                最近更新 更多