Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use foreach for a property in C#

Tags:

c#

I define a property like this :

public IMAGE_DOS_HEADER  ImageDosHeader 
        {

            get
            {
                return imageDosHeader; 
            }
        }

where IMAGE_DOS_HEADER is a struct like this

public struct IMAGE_DOS_HEADER
        {      // DOS .EXE header
            public UInt16 e_magic;              // Magic number
            public UInt16 e_cblp;               // Bytes on last page of file
            public UInt16 e_cp;                 // Pages in file
            public UInt16 e_crlc;               // Relocations
            public UInt16 e_cparhdr;            // Size of header in paragraphs
            public UInt16 e_minalloc;           // Minimum extra paragraphs needed
         }

and finally I want use this property in main program using foreach like this

foreach (var DosHeader in reader.ImageDosHeader)
       {
           listView2.Items[i].SubItems.Add(DosHeader.ToString("X"));
           i++;
       }

but an compile error occured: " Error 1 foreach statement cannot operate on variables of type 'PEfileReader.PeHeaderReader.IMAGE_DOS_HEADER' because 'PEfileReader.PeHeaderReader.IMAGE_DOS_HEADER' does not contain a public definition for 'GetEnumerator"

anybody can help me?

like image 812
user1510265 Avatar asked Dec 12 '25 12:12

user1510265


1 Answers

To get fields of a struct you should use reflection

IMAGE_DOS_HEADER header = new IMAGE_DOS_HEADER() { e_cblp = 1, e_cp = 2, e_cparhdr = 3, e_crlc = 4, e_magic = 5, e_minalloc = 6 };

var fieldsAndValues = 
        typeof(IMAGE_DOS_HEADER)
        .GetFields()
        .Select(f=>new {
            Name= f.Name,  //<== Name of the field
            Value = f.GetValue(header) //<==Value of the field
        })
        .ToList();

Then you can insert the values to a listview

foreach (var item in fieldsAndValues)
{
    listView2.Items[i].SubItems.Add(item.Value);
}
like image 52
L.B Avatar answered Dec 15 '25 03:12

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!