简体   繁体   中英

iterate through variables in a class c#

I'm trying to get a list of all the variables in a class. I'm trying to use reflection (which I've never used before) but it just doesn't make sense, and the docs aren't helping either. I feel like I'm making an obvious mistake, but I can't figure it out.

        public override string ToString()
        {
            FieldInfo[] fields = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            List<string> _return = new List<string>();
            foreach (var field in fields)
            {
                _return.Add(field.Name + ": " + field.GetValue(field));
            }
            return _return;
        }

The output is nothing.

This will do what you are looking for:

public override string ToString()
    {
        FieldInfo[] fields = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        List<string> _return = new List<string>();
        foreach (var field in fields){
             _return.Add(field.Name + ": " + field.GetValue(this));
          }
    return string.Join(",", _return);
}

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