获取具有 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
...

如何从标识符 NameSyntax 中检索衍生类(而不是 BaseClass((假设它始终是一个属性(

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

你试过吗

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

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

最新更新