简体   繁体   中英

Getting type of the caller of a property with Roslyn

I'm writing a CSharpSyntaxRewriter and trying to get the type of a property node's owner. I cannot retrieve it correctly when there is class inheritance.

The sample code being parsed

class BaseClass
{
    public string MyProperty => "hello";
}

class DerivedClass : BaseClass
{
    void MyMethod()
    {
        var withThis = this.MyProperty == "hello";
        var withoutThis = MyProperty == "hello";
    }
}

Code of the CSharpSyntaxRewriter

...
// this.MyProperty or object.MyProperty, used by first line of MyMethod
var memberAccess = node as MemberAccessExpressionSyntax;
if (memberAccess?.Name.Identifier.Text == "MyProperty")
{
    var type = SemanticModel.GetTypeInfo(memberAccess.Expression).Type; // type is DerivedClass
...
...
// MyProperty (MyProperty access without this), used by second line of MyMethod
var identifier = node as IdentifierNameSyntax;
if (identifier?.Identifier.Text == "MyProperty")
{
    var type2 = SemanticModel.GetTypeInfo(identifier).Type; // type is string
    var symbolInfo = SemanticModel.GetSymbolInfo(identifier);
    var type = symbolInfo.Symbol.ContainingType; // type is BaseClass
    var ds = SemanticModel.GetDeclaredSymbol(identifier); // null
    var pp = SemanticModel.GetPreprocessingSymbolInfo(identifier); // empty
...

How could I retrieve DerivedClass (instead of BaseClass) from the identifierNameSyntax (assuming its always a property)

I guess it is possible by getting it from ancestor nodes (from method or class declaration), but still wondering if is there a better way?

Did you try

var containingClass = node;
while (!(containingClass is ClassDeclrationExpressionSyntax))
{
    containingClass = containingClass.Parent;
}

There can be some problems with Generics\\Nested classes, but they are solvable.

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