Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the fields of a struct

Tags:

c#

reflection

Why does the following code produce no output?

static void Main(string[] args)
{
    FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public);
    foreach (FieldInfo info in fi)
    {
        Console.WriteLine(info.Name);
    }
}

public struct MyStruct
{
    public int one;
    public int two;
    public int three;
    public int four;
    public int five;
    public int six;
    public bool seven;
    public String eight;
}
like image 357
Odrade Avatar asked Jun 15 '09 18:06

Odrade


People also ask

How do I extract a field from a structure in Matlab?

Extract Fields From Structurehold on plot(extractfield(roads,'X'),extractfield(roads,'Y')); plot(extractfield(r,'X'),extractfield(r,'Y'),'m'); Extract the names of the roads, stored in the field STREETNAME . The field values are character vectors, so the result is returned in a cell array.

What is field in struct?

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A class or struct may have instance fields, static fields, or both. Instance fields are specific to an instance of a type.

Can a field in a struct be an array?

The names and number of fields within the STRUCT are fixed. Each field can be a different type. A field within a STRUCT can also be another STRUCT , or an ARRAY or a MAP , allowing you to create nested data structures with a maximum nesting depth of 100.

How do you convert a struct to a table?

T = struct2table( S ) converts the structure array, S , to a table, T . Each field of S becomes a variable in T . T = struct2table( S , Name,Value ) creates a table from a structure array, S , with additional options specified by one or more Name,Value pair arguments.


1 Answers

You need to or in the instance binding as well. Change your code to:

FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo info in fi)
{
    Console.WriteLine(info.Name);
}
like image 106
Jake Pearson Avatar answered Oct 06 '22 21:10

Jake Pearson