Pregunta

I am trying to write some equivalent C# code to the following Java one:

public class XLexer extends antlr.CharScanner implements TokenStream {
protected int stringCtorState = 0;

public String mString() { return ""; }

public Token nextToken()  {
       resetText(); // exists in CharScanner class
       return null; // will return something
}

public TokenStream plumb() {
    return new TokenStream() {
        public Token nextToken()  {
            resetText(); // exists in CharScanner class
            if (stringCtorState >= 0) { String x = mString(); }
            return null; // will return something
        }
    };
}

}

Can anyone give me an hint how to do it in C# because I am getting errors when defining the method nextToken inside the return statement.

thanks!

¿Fue útil?

Solución

There are no anonymous classes in C# (in the sense you need). If you want to return an instance of a custom implementation of TokenStream, you need to define it and give it a name.

Eg.:

public MyTokenStream {
    public Token nextToken() {
        // ...
    }
}

public TokenStream plumb() {
    return new MyTokenStream();
}

See:

for reference.

As kan remarked, in C# (and Java 8, too) you would typically use a delegate or a lambda instead. If all that TokenStream does is returning a nextToken, it could be implemented like so:

    public class TokenStream
    {
    }

    public class SomeClass
    {            
        public Func<TokenStream> Plumb()
        {
            // I'm returning a function that returns a new TokenStream for whoever calls it
            return () => new TokenStream();
        }
    }

    static void Main(string[] args)
    {
        var someClass = new SomeClass();
        TokenStream stream = someClass.Plumb()(); // note double brackets
    }

Think first-class functions in JavaScript, if it helps to grok it.

New Java brings functional interfaces, which is similar: http://java.dzone.com/articles/introduction-functional-1

Otros consejos

Use delegates instead. An example here: http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

Not sure if this is your desired result.

but the way I see it is you just want to return a TokenStream object which has the method of nextToken which returns an object Token

public class TokenStream
{
    public Token nextToken()
    {
         return new Token();
    }
}

that would be your TokenStream class and then you could have a method/function else where which does the following

public TokenStream plumb()
{
    return new TokenStream();
}

the usage of which would be

TokenStream ts = plumb();
Token t = ts.nextToken();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top