[英]Getting the name of a type of generic property of class definition using Roslyn
我有一個定義如下的類:
class Derived
{
public int t { get; set; }
public List<Child> Childs { get; set; }
}
我想為類的每個屬性獲取System.Type
。 這是我目前所擁有的:
var properties = node.DescendantNodes().OfType<PropertyDeclarationSyntax>();
var symbolDisplayFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces
);
foreach (var property in properties)
{
var typeSymbol = context.SemanticModel.GetSymbolInfo(property.Type).Symbol as INamedTypeSymbol;
string name = typeSymbol.ToDisplayString(symbolDisplayFormat);
}
其中 node 是ClassDeclarationSyntax
。
此代碼適用於屬性t
; 屬性類型的名稱返回System.Int32
。 但是,對於Childs
屬性(它是具有泛型參數的類型),我得到一個 null typeSymbol
,它不是預期的此屬性的System.Type
。
如何使用 Roslyn 從類定義中獲取泛型類型的屬性類型?
您應該使用SemanticModel.GetTypeInfo
而不是SemanticModel.GetSymbolInfo
從節點檢索相應的ITypeSymbol
:
...
foreach (var property in properties)
{
var info = context.SemanticModel.GetTypeInfo(property);
var typeSymbol = info.Type ?? info.ConvertedType;
...
}
如果你想要泛型的(第一個)參數類型,你可以使用:
TypeSyntax type = (property.Type as GenericNameSyntax).TypeArgumentList.Arguments[0];
我設法通過以下方式獲取通用類型信息:
if (type is INamedTypeSymbol nType) //type is ITypeSymbol
{
bool isGeneric = nType.IsGenericType;
int typeArgumentsCount = nType.TypeArguments.Count();
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.