簡體   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