0

通过下面的课程,我尝试获得:

  • 字段名称
  • 价值

我试过这段代码:

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

但我的字典里什么都没有。

任何想法 ?

  [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;     
}
4

2 回答 2

0

尝试这个

const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
于 2013-10-21T11:49:49.433 回答
0

是的,我认为这会起作用:

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

上述代码仅适用于未经修改的实例字段

于 2013-10-21T11:51:12.847 回答