Usando la variable de cadena de un objeto en una declaración de cambio

I'm trying to figure out why I'm getting this error:

    switch (token.type.GetName()) 
            CompoundStatementParser compoundParser = new CompoundStatementParser(this);
            statementNode = compoundParser.parse(token);

GetName() y name both return strings. This is what the object looks like:

    public static readonly PascalTokenType BEGIN = new PascalTokenType("BEGIN");

I know I could get around this problem by changing it to an if statement but when this is complete I'm going to have at least 20 conditions so I'd rather not. I'm supposing it's because isn't assigned until runtime?

preguntado el 21 de mayo de 12 a las 19:05

If you know the conditions ahead of time (big assumption on my part), why not create an enum for it and compare based on that? -

So pass an enum to the PascalTokenType constructor instead of a string? -

1 Respuestas

Yeah, you have the right idea. The problem is that this value could change at runtime, which the compiler doesn't like.

contestado el 21 de mayo de 12 a las 19:05

Once BEGIN is created it will never change. Is there a way to create an immutable object with immutable members that the compiler will accept in a switch condition? - david demar

It's not enough that you know it won't change. It's that the compiler doesn't know it won't change. There are probably some workarounds, but I find that when I am trying to fit a square peg in a round hole, I am usually approaching the problem wrong. - matar nueve

En lugar de I'm just going to type "BEGIN". Seems to be the most straightforward way to do it without having to rewrite it as if-else. - david demar

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.