Access private fields

前端 未结 4 1699
无人及你
无人及你 2020-12-06 10:07

Is it possible to get or set private fields?

I want to get System.Guid.c. Is there a way to access it or should I just copy the code from the strut and

4条回答
  •  余生分开走
    2020-12-06 10:16

    You can have an extension method to get any private field of any type:

    public static T GetFieldValue(this object obj, string name) {
        var field = obj.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        return (T)field?.GetValue(obj);
    }
    

    And then access a private field of an arbitrary type:

    Guid id = Guid.NewGuid();
    Int16 c = id.GetFieldValue("_c");
    

提交回复
热议问题