简体   繁体   中英

C# How to iterate an objects properties after they have been set from within the object itself?

I want to have a method inside of the object that will return a dictionary list of all it's property names and values dynamically after they have been initialized via the constructor. Something like this:

    public string name;
    public string type;

    public obj(string name, string type)
    {
        this.name = determineName(name)
        this.type = determineType(type)
        this.DictionaryOfValues = createDictionaryOfValues;
    }

    public Dictionary<string, string> createDictionaryOfValues(){
        // iterate name and type above dynamically and return a dictionary
        // with key value as property name and value
    }

I have seen examples of how to easily do it when the object already created but I'm wondering if there is some way to pick and return the values inside the object itself

This worked fine for me. You can filter the fields further with custom attributes.

var fields = from fieldInfo in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
let attributes = fieldInfo.GetCustomAttributes(true).OfType < CustomAttribute > ()
where attributes.Any()
select new {
  fieldInfo.FieldType, fieldInfo.Name, Attribute = attributes.Single(), ar = fieldInfo.GetValue(this)
};

foreach(var field in fields) {
  Console.WriteLine(field.FieldType + " is called " +
    field.Name + " and its value is " +
    field.ar.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM