6

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

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

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

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

4

6 回答 6

17

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

于 2008-09-22T17:10:37.550 回答
4

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

public string Name { get; set;} 

是一个捷径

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

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

于 2008-09-22T17:12:46.203 回答
2

查看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 );
}

但这并不是全部!:)

于 2008-09-22T17:27:20.083 回答
1

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

于 2008-09-22T17:12:23.427 回答
1

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

于 2008-09-22T17:12:59.463 回答
1

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

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;
于 2008-09-22T17:18:42.447 回答