简体   繁体   中英

C# 3.0 Auto-Properties - Is it possible to add custom behaviour?

I would like to know if there is any way to add custom behaviour to the auto property get/set methods.

An obvious case I can think of is wanting every set property method to call on any PropertyChanged event handlers as part of a System.ComponentModel.INotifyPropertyChanged implementation. This would allow a class to have numerous properties that can be observed, where each property is defined using auto property syntax.

Basically I'm wondering if there is anything similar to either a get/set template or post get/set hook with class scope.

(I know the same end functionality can easily be achieved in slightly more verbose ways - I just hate duplication of a pattern)

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

No you cannot : auto property are a shortcut for an explicit accessor to a private field. eg

public string Name { get; set;} 

is a shortcut to

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

If you want to put custom logic you must write get and set explicitly.

Look to PostSharp . It is a AOP framework for typicaly issue "this code pattern I do hunderd time a day, how can I automate it?". You can simplify with PostSharp this ( for example ):

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

to

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

But this is not all! :)

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

You could consider using PostSharp to write interceptors of setters. It is both LGPL and GPLed depending on which pieces of the library you use.

The closest solution I can think of is using a helper method:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM