[英]How to validate a parameter's type in method when using Roslyn
I'm doing code analysis with Roslyn in order to validate that even though I have the following signature 我正在与Roslyn进行代码分析,以验证这一点,即使我具有以下签名
public void MyMethod(object anObject, MyCustomObject customObject);
I only want to receive, as parameters, a string (1st) and a child from MyCustomObject (2nd). 我只想从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). 到目前为止,我可以从属性Parameters(symbol.Parameters)操作IParameterSymbol对象。 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.
我没有得到以下内容:我已经检查了包含两个参数的IEnumerable结果,但是由于方法签名,它希望接收一个对象和一个MyCustomObject实例。 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.
我目前无法确定第一个参数确实是对象而不是字符串(仅是示例,可能是其他任何东西),并且当我期望MyCustomObject的孩子时,如果我给它一个null,我想知道它是一个null参数。
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对象时,这是给我什么样的信息:
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
What you should be doing is getting the arguments (not parameters -- they are different things!) and calling SemanticModel.GetTypeInfo()
on the ArgumentSyntax. 您应该做的是获取参数(而不是参数-它们是不同的东西!)并在ArgumentSyntax上调用
SemanticModel.GetTypeInfo()
。 That'll give you the type of the expression being passed. 这将为您提供要传递的表达式的类型。 From there you can do whatever checks you need.
从那里您可以进行所需的任何检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.