I'm trying to create an attribute with PostSharp to implement specific backing fields of properties. However I did not find any helpful answers in the documentation, official examples or here on SO.
Here's an example of what I'm trying to do:
[WrappedProperty]
public int MyProperty { get; set; }
will compile to
private WrapperClass<int> _generatedBackingField_myProperty;
public int MyProperty
{
get => _generatedBackingField_myProperty.Value;
set => _generatedBackingField_myProperty.Value = value;
}
Is there any way to achieve this with PostSharp?
I found the answer, you can use LocationInterceptionAspect
to intercept properties.
So the code would look like this:
[PSerializable]
public class WrappedProperty : LocationInterceptionAspect
{
private WrapperClass<object> _backingField;
public override void OnGetValue(LocationInterceptionArgs args)
{
InitBackingField();
args.Value = _backingField.Value;
}
public override void OnSetValue(LocationInterceptionArgs args)
{
InitBackingField();
_backingField.Value = args.Value;
}
}