C# Reflection - changing the value of a field of a variable

后端 未结 3 429
轮回少年
轮回少年 2021-01-01 01:40

I have an instance of a class, I want to change an object data member of this instance only with another object of the same type (swap), due to my system c

相关标签:
3条回答
  • 2021-01-01 02:07

    Yes, its 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 a hidden (private/protected/internal) field. Use the corresponding FieldInfo.GetValue(...) to read; combine the two trivially to get your desired swapping operation.

    Don't hold me to the BindingFlags (I always seem to get those wrong on the first attempt) or the exact syntax, but that's basically it.

    Look over System.Reflection for reference.

    0 讨论(0)
  • 2021-01-01 02:09

    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(Of cartonclass, Integer)(cartonyoudropped, "survivingeggcount", 3)

    0 讨论(0)
  • 2021-01-01 02:12

    If you use .NET 3.5, you can use my open-source library, Fasterflect, to address that with the following code:

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

    When using Fasterflect, you don't have to bother with the right BindingFlags specification and the performance implication (as when using reflection).

    0 讨论(0)
提交回复
热议问题