mpen
mpen

Reputation: 282895

Get public fields?

I've got a struct defined like this

private struct Combinators
{
    public const char DirectChild = '>';
    public const char NextAdjacent = '+';
    public const char NextSiblings = '~';
    public const char Descendant = ' ';
}

I want to use reflection to get a list of all the values of the public const char fields in the struct (as specific as possible). How can I do that?

Upvotes: 1

Views: 1083

Answers (2)

mpen
mpen

Reputation: 282895

private class TypedEnum<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
        return GetType().GetFields().Select(f => f.GetValue(null)).OfType<T>().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

private class Combinators : TypedEnum<char>
{
    public const char DirectChild = '>';
    public const char NextAdjacent = '+';
    public const char NextSiblings = '~';
    public const char Descendant = ' ';
}

Edit: Blah... there's no way to make a static IEnumerable is there?

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77546

var fieldValues = typeof(Combinators)
    .GetFields()
    .Where(x => x.FieldType == typeof(char) && x.IsLiteral)
    .ToDictionary(x => x.Name, x => (char)x.GetValue(null));

Returns a Dictionary<string, char> where the key is the field name, and the value is the field value (as a character).

Update: Added where clause based on comments and @nasufara's suggestion, and added IsLiteral check based on @Jeff M's.

Upvotes: 7

Related Questions