xsharp.eu • Send() and IVarPut()/IVarGet() in X#
Page 1 of 1

Send() and IVarPut()/IVarGet() in X#

Posted: Fri Aug 12, 2016 4:30 am
by wriedmann
Sometimes, you could need a functionality like the Send(), IVarPut() and IVarGet() functions from Clipper also in X#
Fortunately, thanks to Reflection, this is possible, and thanks to the possibility to use extension methods, also easier to use.

A sample use could be:

Code: Select all

oObject:Send( cMethodName, oParameter ) 
oObject:PropertyPut( cPropertyName, oValue )
oValue := oObject:PropertyGet( cPropertyName )
This is the extension class that gives this functionality:

Code: Select all

using System                        
using System.Text
using System.Runtime.InteropServices
using System.Reflection 
using System.Diagnostics

static class ObjectExtensions

static method Send( self oObject as object, cMethod as string, aParameters as object[] ) as object 
local oType as System.Type
local oReturn as object
local oInfo as MethodInfo
	
oType := oObject:GetType()
oReturn := null_object
oInfo := oType:GetMethod( cMethod )
if oInfo != null_object
    oReturn := oInfo:Invoke( oObject, aParameters )
endif
	
return oReturn              

static method PropertyGet( self oObject as object, cPropertyName as string ) as object
local oReturn as object	
local oInfo as System.Reflection.PropertyInfo
	
oInfo := oObject:GetType():GetProperty( cPropertyName ) 
if oInfo != null_object                                  
    oReturn := oInfo:GetValue( oObject, null_object ) 
else
    oReturn			:= null_object
endif
	
return oReturn

static method PropertyPut( self oObject as object, cPropertyName as string, oValue as object ) as void
local oInfo as System.Reflection.PropertyInfo
	
oInfo := oObject:GetType():GetProperty( cPropertyName )
if oInfo != null_object
    oInfo:SetValue( oObject, oValue, null_object )                        
endif
	
return

end class

Send() and IVarPut()/IVarGet() in X#

Posted: Mon Aug 15, 2016 2:27 pm
by robert
Wolfgang,

Nice how you have used the extension method to extend the OBJECT type and therefore make the methods available in every type.
This is in fact very similar to what happens in the Vulcan Runtime and what will happen in the new XSharp runtime for the Send() function and IVarGet() and IVarPut() functions.

The biggest difference for these functions is that they cache the MethodInfo and PropertyInfo and for properties that they also do a lookup for (public) fields, since the VO language allows late bound access to public fields as well.

Robert