2015-10-29 1 views
1

Besoin de trouver TypeSyntax ou essentiellement Type d'un spécifique classé en classe en utilisant Roslyn.
Quelque chose comme ceci:Comment trouver le type du champ avec le nom spécifique dans Roslyn

rootSyntaxNode 
.DescendantNodes() 
.OfType<FieldDeclarationSyntax>() 
.First(x => x.Identifier="fieldName") 
.GivemeTypeSyntax() 

Mais n'a pas pu obtenir aucune indication sur la façon d'atteindre Identifier et SyntaxType dans le nœud FieldDeclarationSyntax. Une idée s'il vous plaît?

Répondre

5

Une partie du problème est que les champs peuvent contenir plusieurs variables. Vous regarderez Declaration pour le type et Variables pour les identifiants. Je pense que c'est ce que vous cherchez:

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 }); 

var fields = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>(); 

//Get a particular variable in a field 
var second = fields.SelectMany(n => n.Declaration.Variables).Where(n => n.Identifier.ValueText == "secondVariable").Single(); 
//Get the type of both of the first two fields. 
var type = fields.First().Declaration.Type; 
//Get the third variable 
var third = fields.SelectMany(n => n.Declaration.Variables).Where(n => n.Identifier.ValueText == "thirdVariable").Single(); 
+0

Peut-être que je suis confus par ce qu'est un "champ", mais ce ne serait pas 3 champs et 3 variables? Est-ce que mean n'est pas «int first, second», juste un synonyme abrégé pour «int first»; int second, 'ou est-ce que je manque quelque chose? –