简体   繁体   中英

Roslyn: detect when a local variable has been declared with `using`

I'm writing a C# source generator (similar to analyzer) and I'm trying to determine if a local variable (ILocalSymbol) is readonly due to being declared with a using directive. Specifically the following case:

using System;

struct Container : IDisposable
{
    public void Dispose() {}
}

public class C {
    public void M() {
        using (var container = new Container())
        {
            var otherCon = new Container();
            
            // I want to detect when the following would throw an error
            //container = otherCon;
        }
    }
}

Roslyn doesn't seem to have any public APIs for this as far as I can tell. LocalSymbol has IsUsing but that is an internal type. Same deal with DeclarationKind.

The only way I found to do this was by examining the declaring syntax for the variable:

var isWritable = true;
var declaringSyntax = symbol.OriginalDefinition.DeclaringSyntaxReferences.FirstOrDefault();
if (declaringSyntax?.GetSyntax().Parent is VariableDeclarationSyntax 
  variableDeclarationSyntax && variableDeclarationSyntax?.Parent is UsingStatementSyntax)
    isWritable = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM