我們可以從Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax獲取System.Type或實質上完全限定的類型名稱嗎?問題是,TypeSyntax返回類型的名稱,因爲它是用可能不是完全合格的類名稱的代碼編寫的,我們無法從中找到類型。我們可以從Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax獲取System.Type嗎?
2
A
回答
5
要獲得一段語法的全限定名稱,您需要使用SemanticModel
來獲得對其符號的訪問權限。我已經在我的博客上撰寫了語義模型指南:Learn Roslyn Now: Introduction to the Semantic Model
根據您的previous question,我假設您正在查看字段。
var tree = CSharpSyntaxTree.ParseText(@"
class MyClass
{
int firstVariable, secondVariable;
string thirdVariable;
}");
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { mscorlib });
//Get the semantic model
//You can also get it from Documents
var model = compilation.GetSemanticModel(tree);
var fields = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>();
var declarations = fields.Select(n => n.Declaration.Type);
foreach (var type in declarations)
{
var typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol;
var fullName = typeSymbol.ToString();
//Some types like int are special:
var specialType = typeSymbol.SpecialType;
}
您還可以得到符號的聲明本身(而不是用於對聲明的類型)通過:
var declaredVariables = fields.SelectMany(n => n.Declaration.Variables);
foreach (var variable in declaredVariables)
{
var symbol = model.GetDeclaredSymbol(variable);
var symbolFullName = symbol.ToString();
}
最後一點:這些符號調用.ToString()
給你他們的完全合格名稱,但不包括其完全限定的元數據名稱。 (嵌套類在之前,其類名和泛型處理方式不同)。
相關問題
- 1. 我們可以從HBase表中獲取所有列名嗎?
- 2. 我們可以從Twitter oauth API獲取電子郵件ID嗎?
- 3. 我們可以使用JavaScript從網頁獲取數據嗎?
- 4. 我們可以從slickgrid獲取所有的值嗎?
- 5. 我們可以從ASP.NET獲取PHP文件的返回值嗎?
- 6. 我們可以從DialPlan Ping延伸嗎?
- 7. 我們可以在iOS中獲取iOS系統鈴聲嗎?
- 8. 我們可以使用javascript訪問/獲取數據嗎?
- 9. 我們可以在Window phone 7.1中獲取位置區號嗎?
- 10. 我們可以使用arduino.getKey()獲取鍵盤事件嗎?
- 11. 我們可以在iframe中獲取元素嗎?
- 12. 我們可以使用SQLAlchemy獲取postgres數據庫轉儲嗎?
- 13. 我們可以使用「this」指針獲取對象名稱嗎
- 14. 獲取我們從
- 15. 我們可以從netstat命令中獲得流逝時間嗎
- 16. 我們可以從Worldweatheronline api獲得多個天氣數據嗎?
- 17. 我們可以從evernote文件中提取文本內容嗎
- 18. 我們可以從刻錄設置中提取msi文件嗎?
- 19. 我們可以使用java從MySql數據庫獲取添加的圖像嗎?
- 20. 我們可以從Android Facebook Sdk中獲取用戶的出生日期嗎?
- 21. 我們可以使用從XSLT中的數據庫表中獲取的值嗎?
- 22. Yammer API - 我們可以從當前用戶的yammer API獲取組列表嗎?
- 23. 我們可以從USB閃存驅動器獲取VID和PID嗎?
- 24. 我們可以從DateSetListener中獲取Date引用的日期選擇器Dialog嗎?
- 25. 我可以從Kibana可視化中獲取消息嗎?
- 26. 我可以從InstallShield可執行文件獲取ProductCode嗎?
- 27. 我可以通過NSURLResponse獲取URL嗎?
- 28. 可以從file.OpenStreamForWriteAsync()獲取file.OpenStreamForReadAsync()嗎?
- 29. 我們可以從Facebook應用獲取哪些信息?
- 30. 我可以從Javascript獲得iOS6 IDFA嗎?
請注意,您無法輕鬆獲取System.Type,但可以獲取Microsoft.CodeAnalysis.ITypeSymbol。喬希的回答已經給出了一個很好的解釋。請注意,在大多數情況下,System.Type實際上並不是您想要的,因爲這意味着您的流程中會以不需要的方式加載類型。 –