簡體   English   中英

使用Roslyn派生參數類型

[英]Derive parameter type with Roslyn

我創建了以下對象來遍歷我的構造函數:

internal class ConstructorWalker : CSharpSyntaxWalker
{
    private string className = String.Empty;
    private readonly SemanticModel semanticModel;
    private readonly Action<string> callback;

    public ConstructorWalker(Document document, Action<string> callback)
    {
        this.semanticModel = document.GetSemanticModelAsync().Result;
        this.callback = callback;
    }

    public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
    {
        var typeToMatch = typeof(Dictionary<string, Func<GenericMobileRequest, Result<object>, Task>>);
        var parameters = node.ParameterList;

        foreach (var param in parameters.ChildNodes()) {
            //This does not work... .Symbol is null
            var paramType = ((IParameterSymbol)semanticModel.GetSymbolInfo(param).Symbol).Type;
            if(paramType == typeToMatch) {
               //PROFIT!!!
            }
        }

如何確定參數的類型,以便確保它是我感興趣的類型?

使用Roslyn很難輕松獲得參數的實際Type 您可以如下所示獲得TypeSyntaxITypeSymbol ,但是除非使用反射,否則就無法真正獲得Type對象(據我所知)。

string typeToMatchString = "Dictionary<string, Func<Exception, HashSet<object>, Task>>"

foreach (var parameter in node.ParameterList.Parameters)
{
    var typeSyntax = parameter.Type;
    var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).Type;

    // Maybe comparing the name is enough?
    if (typeSymbol.ToDisplayString() == typeToMatchString) 
        //PROFIT???       
}

您可能還想看看這個相關問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM