繁体   English   中英

使用罗斯林获取属性调用者的类型

[英]Getting type of the caller of a property with Roslyn

我正在编写CSharpSyntaxRewriter并尝试获取属性节点所有者的类型。 有类继承时,我无法正确检索它。

样本代码被解析

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

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

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
...

我怎么能从identifierNameSyntax检索DerivedClass(而不是BaseClass)(假设它始终是一个属性)

我想可以通过从祖先节点(通过方法或类声明)获取它,但是仍然想知道是否有更好的方法?

你试过了吗

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

泛型\\嵌套类可能存在一些问题,但可以解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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