我正在编写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)(假设它始终是属性)
我想从祖先节点(来自方法或类声明)获取它是可能的,但仍然想知道是否有更好的方法?
答案 0 :(得分:0)
你试过吗
var containingClass = node;
while (!(containingClass is ClassDeclrationExpressionSyntax))
{
containingClass = containingClass.Parent;
}
Generics \ Nested类可能存在一些问题,但它们是可以解决的。