As specified in the question, I am interested in using the Dynamic features of .net to cache an object's field getter/setter and calling it at runtime.
Using info from: Is there a way to create a delegate to get and set values for a FieldInfo?
I have put together a class and function that set up the functionality that I need:
Public Class c1
Public someField As Integer 'we will Get the value of this dynamically
End Class
Public Function CreateGetter(Of S, T)(ByVal strFieldName As String) As Func(Of S, T)
'creates a function to return the value
Dim objFieldInfo As FieldInfo
Dim strMethodName As String
Dim objGetterMethod As DynamicMethod
Dim objGen As ILGenerator
objFieldInfo = GetType(S).GetField(strFieldName)
strMethodName = Convert.ToString(objFieldInfo.ReflectedType.FullName) & ".get_" & Convert.ToString(objFieldInfo.Name)
objGetterMethod = New DynamicMethod(strMethodName, GetType(T), New Type(0) {GetType(S)}, True)
objGen = objGetterMethod.GetILGenerator()
If objFieldInfo.IsStatic = False Then
objGen.Emit(OpCodes.Ldarg_0)
objGen.Emit(OpCodes.Ldfld, objFieldInfo)
Else
objGen.Emit(OpCodes.Ldsfld, objFieldInfo)
End If
objGen.Emit(OpCodes.Ret)
Return DirectCast(objGetterMethod.CreateDelegate(GetType(Func(Of S, T))), Func(Of S, T))
End Function
I call this good code with:
Dim getValue = CreateGetter(Of c1, Integer)("someField")
Dim someValue As Integer
someValue = getValue(o1)
However, the part I am stumped at is how to modify function CreateGetter
to be able to use it in a cached form like: (caching the instance object)
Dim getValue = CreateGetter(Of c1, Integer)(o1,"someField")
Dim someValue As Integer
someValue = getValue()
I realize this may require some modding of the IL code in CreateGetter
but that is the tricky part that I am stuck at.