C # Reflection - changing the value of a variable field

I have an instance of a class, I want to change the data member of the object of this instance only with another object of the same type (swap), due to my system limitations I cannot use =, new or setter operators.

Basically, I would like to change the value of a variable field, a field is an object contained within another object - the variable that its instance has.

Can reflection be used? if yes, then someone please give me the main direction?

Thanks yoav

+6
reflection c #
source share
3 answers

Yes it is possible.

In short, do something like

Type typeInQuestion = typeof(TypeHidingTheField); FieldInfo field = typeInQuestion.GetField("FieldName", BindingFlags.NonPublic | BindingFlags.Instance); field.SetValue(instanceOfObject, newValue); 

to change the value of the hidden (private / protected / internal) field. Use the appropriate FieldInfo.GetValue(...) to read; combine the two trivially to get the desired replacement operation.

Do not keep me in BindingFlags (I always seem to be mistaken on my first try) or the exact syntax, but basically that.

See System.Reflection for help.

+13
source share

If you are using .NET 3.5, you can use my open source library, Fasterflect , to access this using the following code

 typeof(MyType).SetField("MyField", anotherObject); 

When using Fasterflect, you donโ€™t have to worry about the correct BindingFlags specification and performance implication (as with reflection).

+4
source share

in vb with generics, but rudimentary error handling:

 Module somereflectionops Function GetFieldValue(Of OBTYPE, FIELDTYPE)(instance As OBTYPE, fieldname As String, Optional specbindingflags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance) As FIELDTYPE Dim ot As Type = GetType(OBTYPE) Dim fi As FieldInfo Try fi = ot.GetField(fieldname, BindingFlags.Default Or specbindingflags) If fi Is Nothing Then Return Nothing Return fi.GetValue(instance) Catch ex As Exception Return Nothing End Try End Function Function SetFieldValue(Of OBTYPE, FIELDTYPE)(instance As OBTYPE, fieldname As String, value As FIELDTYPE, Optional specbindingflags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance) As Boolean Dim ot As Type = GetType(OBTYPE) Dim fi As FieldInfo Try fi = ot.GetField(fieldname, BindingFlags.Default Or specbindingflags) If fi Is Nothing Then Return false fi.SetValue(instance, value) Return True Catch ex As Exception Return False End Try End Function End Module 

use: SetFieldValue (cardboard, Integer) (cartonyudropped, "surviveeggcount", 3)

0
source share

All Articles