I am having some difficulty in trying to make a Func<T> expression evaluate a property within an object instance, e.g.
var t = new Transition<ILexeme>( 1, () => TokenType == eToken.TOKEN_COMMENT );
The Visual Studio compiler complains with a An object reference is required for the non-static field, method or, property ‘ILexeme.TokenType.get’ error, because it’s expecting an ILexeme object instance.
What I am attempting to do is create a state machine that uses Func<T> to invoke the transition function’s delegate, which tests to see if the value of the eToken property matches the eToken within the token stream. If it is equal the machine moves onto the next state.
The problem is I am passing in ILexeme as the generic type to the Transition class, but I want the transition function to use a property within the generic type, i.e. TokenType. My question is how can I achieve this bearing
in mind that it must work for value types, i.e. char, int, etc?
Here is the definition for ILexeme:
public interface ILexeme
{
eToken TokenType { get; }
String TokenString { get; }
}
And here is the concrete implementation of ILexeme:
public enum eToken : int
{
TOKEN_COMMENT,
TOKEN_SEPARATOR
}
public class Token : ILexeme
{
public eToken TokenType { get; }
public String TokenString { get; }
}
And this is the definition for Transition:
public readonly int FromState;
public readonly int ToState;
public readonly Func<T> Input;
public Transition( int fromState, Func<T> input, int toState )
{
this.FromState = fromState;
this.ToState = toState;
this.Input = input;
}
I think you have written your lambda expression incorrectly. Since
TokenTypeis an instance property, you should pass an instance of an object to the lambda. Right now it’s parameterless. So, I think it should be something likeAnd the Transition class
Also, you might want to introduce second type parameter to
Transitionclass, so it becomes something quite general:If it’s the case, you might want to place some type constraints using where clause.