I’m trying to make an enum of strings. Here’s what I’ve got so far,
private class TypedEnum<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return GetType().GetFields().Where(f => f.IsLiteral).Select(f => f.GetValue(null)).OfType<T>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
private static class Combinators : TypedEnum<char>
{
public const char DirectChild = '>';
public const char NextAdjacent = '+';
public const char NextSiblings = '~';
public const char Descendant = ' ';
}
But there are two problems with this. (1) It won’t compile because Combinators is static… I can remove that and hide the c’tor though. (2) It’s not enumerable unless I instantiate it, which I don’t need nor want to do. What are my options? Forget about making it enumerable?
I think this is as close as I can get
public struct Combinators
{
public const char DirectChild = '>';
public const char NextAdjacent = '+';
public const char NextSiblings = '~';
public const char Descendant = ' ';
public static IEnumerable<char> ToEnumerable()
{
return typeof(Combinators).GetFields().Where(f => f.IsLiteral)
.Select(f => f.GetValue(null)).OfType<char>();
}
}
But I wish I could put that ToEnumerable() method in a subclass 🙁
Hah! Solved it!
Just have to pass the class itself as a type to
TypedEnum.