我有以下代码:添加新项目类型VAR的变量 - 在具有构造函数和方法声明一个变量
var allclasses = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach (var memcls in allclasses)
{
if (memcls != null)
{
var methodDeclarations = memcls.DescendantNodes().OfType<MethodDeclarationSyntax>();
foreach (var memmeth in methodDeclarations)
{
var paramDeclaratons = memmeth.ParameterList.Parameters;
其中methodDeclarations定义行后,我还想添加一行像下面伪代码:
methodDeclarations.AddRange(
memcls.DescendantNodes().OfType<ConstructorDeclarationSyntax>())
为了具有被返回加入到相同methodDeclarations变量以及所述ConstructorDeclarationSyntax物品;即,具有同一变量中的ConstructorDeclarationSyntax和MethodDeclarationSyntax项目。我怎样才能做到这一点?
我尝试了一些类型强制转换,并使用List代替var for methodDeclarations变量,但随后出现错误,我想在memmeth上访问ParameterList,Identifier和其他属性。
至于另一个伎俩,我尝试使用下面的代码
var methodDeclarations = tree.GetRoot().DescendantNodes()
.Where(c => c is MethodDeclarationSyntax || c is ConstructorDeclarationSyntax);
但随后又给出了稍后在代码中访问参数列表和标识性的错误。
你需要告诉我们更多关于有问题的类。例如,如果您将methodDeclarations设置为该类型的列表,那么“MethodDeclarationSyntax”和“ConstructorDeclarationSyntax”的常见基类型是什么,那么您应该可以将它们添加到同一个列表中。当然,如果该基类没有“ParameterList”属性,那么你尝试访问它就会失败。你会在这种情况下发生什么? – Chris
这些是Microsoft.CodeAnalysis.CSharp.Syntax名称空间中的Roslyn类型,如下所述:http://www.coderesx.com/roslyn/html/9139EA6B.htm MethodDeclarationSyntax和ConstructorDeclarationSyntax都具有ParameterList和Identifier属性,但它们的基类BaseMethodDeclarationSyntax ,例如没有标识符属性 – Supernova
您是否尝试过'List methodDeclarations = ...',因为这看起来是基本类型? –
Equalsk