0

With the class below, I try to get :

  • field name
  • value

I tried this piece of code :

Dictionary<string, string> listField = 
        membership.GetType()
            .GetFields(BindingFlags.NonPublic)
            .ToDictionary(f => f.Name,
                          f => (string)f.GetValue(null));

but I have nothing in the dictionary.

Any idea ?

  [System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="MyClass", Namespace="http://model.common.party.ent.gfdi.be")]
[System.SerializableAttribute()]
public partial class MyClass : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

    [System.NonSerializedAttribute()]
    private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private string firstName;

    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private string lastName;

    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private System.Nullable<long> fieldA;   

    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private bool fieldB;    

    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private int fieldC;     
}
TheBoubou
  • 19,487
  • 54
  • 148
  • 236
  • 2
    I think you might be missing some binding flags, I'm no reflection guru but I remember having to specify `BindingFlags.Instance` to get instance level fields, (and vice versa for statics) – Charleh Oct 21 '13 at 11:47
  • They are private fields. Why are you trying to serialize/deserialize them and why are you trying to get their values? Make them public instead. – David Arno Oct 21 '13 at 11:49
  • Closer guys is not only find private but find private AND values – TheBoubou Oct 21 '13 at 12:00

2 Answers2

0

try this

const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Yaugen Vlasau
  • 2,148
  • 1
  • 17
  • 38
0

Yeah I think this will work:

Dictionary<string, string> listField =
membership.GetType()
         .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) // <-- specify that you want instance fields
         .ToDictionary(f => f.Name,
                       f => (string)f.GetValue(membership)); // <-- IMPORTANT, 
                       // you need to specify an instance to get a value from a non-static field

The above code will only work for instance fields without modification

Charleh
  • 13,749
  • 3
  • 37
  • 57