How to validate a parameter's type in method w

2019-03-01 13:21发布

问题:

I'm doing code analysis with Roslyn in order to validate that even though I have the following signature

public void MyMethod(object anObject, MyCustomObject customObject);

I only want to receive, as parameters, a string (1st) and a child from MyCustomObject (2nd). I have no power over the signature, it cannot be changed.

Here's what I did to evaluate my method (Here's a snippet)

    public void OnMethodInvocation(SyntaxNodeAnalysisContext context)
    {
        var invocation= context.Node as InvocationExpressionSyntax;
        var symbol = context.SemanticModel.GetSymbolInfo(invocation).Symbol as IMethodSymbol;

        if (symbol?.Name.ToString()== "MyMethod")
        {
            var parameterList = invocation.Parameters;
        }

As of now, I can manipulate my IParameterSymbol objects from the property Parameters (symbol.Parameters). What I don't get is the following : I've gone through my result IEnumerable containing both my parameters, but because of the method signature, it expects to receive an object and a MyCustomObject instances. I'm not in a position (at the moment) to be certain that the first parameter is indeed an object and not a string (merely an example, could have been anything else) and that when I'm expecting a child of MyCustomObject, if I give it a null, I want to know it's a null parameter.

I'll be grateful to anyone who can un-stuck me from this sticky situation !

UPDATES

Here's what kind of information is given to me when I get into an ArgumentSyntax object :

ArgumentSyntax Argument exception
    ContainsAnnotations: false
    ContainsDiagnostics: false
    ContainsDirectives: false
    ContainsSkippedText: false
    Expression: IdentifierNameSyntax IdentifierName exception
    FullSpan: {[550..559)}
    HasLeadingTrivia: false
    HasStructuredTrivia: false
    HasTrailingTrivia: false
    IsMissing: false
    IsStructuredTrivia: false
    KindText: "Argument"
    Language: "C#"
    NameColon: null
    Parent (Microsoft.CodeAnalysis.SyntaxNode): ArgumentListSyntax ArgumentList (exception,exception)
    ParentTrivia: SyntaxTrivia None 
    RawKind: 8638
    RefOrOutKeyword: SyntaxToken None 
    Span: {[550..559)}
    SpanStart: 550

回答1:

What you should be doing is getting the arguments (not parameters -- they are different things!) and calling SemanticModel.GetTypeInfo() on the ArgumentSyntax. That'll give you the type of the expression being passed. From there you can do whatever checks you need.