Method Call Aspects

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.


Method Call Aspects are aspects that can override the behavior of a specific method call. They can be associated with a method and if the namespace the aspect is defined in is in the uses list, it will call the aspect and let it override the behavior of the call:

type
   [MethodAspect(typeof(DateTime), false, 'ToString')]
// this specifies what type & method it should override.
// Note that this is a specific call, the parameters, if any
// go after the 'ToString' as more parameters
   DateTimeToStringDecorator = public class(IMethodCallDecorator, 
IBaseAspect)
   public
     method ProcessMethodCall(aContext: IContext; aMethod: IMethod; 
aValue: ParameterizedValue): Value;
   end;

implementation

method DateTimeToStringDecorator.ProcessMethodCall(aContext: IContext; 
aMethod: IMethod; aValue: ParameterizedValue): Value;
begin
   result := new BinaryValue('DateTime: ', aValue, BinaryOperator.Add);
end;

// Returns 'DateTime: '+OriginalValue

When used from a different assembly: Console.WriteLine(Datetime.Now.ToString);

It emits: DateTime: 12/10/2009 2:41:24 PM


It is also possible to create macro like expressions:

namespace ClassLibrary17;

interface

uses
   System.Runtime.CompilerServices,
   RemObjects.Oxygene.Cirrus,
   RemObjects.Oxygene.Cirrus.Values;

type
   [MethodAspect(typeof(DateTimeSpecialExtensions), true, 
'ToSoapDateTime', typeof(DateTime))]
// Points to the extension method below
// and overrides all calls to this method.
   DateTimeToStringDecorator = public class(IMethodCallDecorator, 
IBaseAspect)
   public
     method ProcessMethodCall(aContext: IContext; aMethod: IMethod; 
aValue: ParameterizedValue): Value;
   end;

   [Extension]
   DateTimeSpecialExtensions = public class
   private
   public
     [Extension]
     class method ToSoapDateTime(aSelf: DateTime): String; empty;
     // There's no need to actually implement this, as it won't ever
     // get called. The decorator will replace it with the actual call
     // and because it doesn't depend on this assembly after that, it will
     // drop the reference, effectively becoming a macro.
   end;

implementation

method DateTimeToStringDecorator.ProcessMethodCall(aContext: IContext; 
aMethod: IMethod; aValue: ParameterizedValue): Value;
begin
   exit new ProcValue(
     ProcValue(aValue).Parameters[0], 'ToString',
     "yyyy'-'MM'-'dd'T'HH':'mm':'ss");
end;


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox