代码之家  ›  专栏  ›  技术社区  ›  morechilli

C#3.0自动属性-是否可以添加自定义行为?

  •  6
  • morechilli  · 技术社区  · 16 年前

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

    我能想到的一个明显的例子是希望每个set属性方法调用任何 PropertyChanged System.ComponentModel.INotifyPropertyChanged

    基本上,我想知道是否有类似于get/set模板或具有类作用域的post get/set钩子的东西。

    (我知道同样的最终功能可以通过稍微详细一点的方式轻松实现——我只是讨厌模式的重复)

    6 回复  |  直到 11 年前
        1
  •  17
  •   John Sheehan    16 年前

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

        2
  •  4
  •   Patrick D'Souza ob1    11 年前

    否不能:自动属性是专用字段显式访问器的快捷方式。例如

    public string Name { get; set;} 
    

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

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

        3
  •  2
  •   TcKs    16 年前

    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
  •  1
  •   Joseph Daigle Sarabpreet Singh Anand    16 年前

        5
  •  1
  •   Justin Rudd    16 年前

    你可以考虑使用 PostSharp 编写setter的拦截器。它是LGPL和GPLed,具体取决于您使用的库的哪些部分。

        6
  •  1
  •   Mark Cidade    16 年前

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

    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;