Reading the default namespace through Roslyn API

后端 未结 2 1667
我寻月下人不归
我寻月下人不归 2021-01-22 15:55

Is there a way to read the default namespace setting from the IProject interface or any other Roslyn interface? I know that I can parse the project\'s file but I think this shou

相关标签:
2条回答
  • 2021-01-22 16:12

    Unfortunately, Roslyn does not expose a way to do that at the moment, but I agree that it is something we will probably need eventually.

    0 讨论(0)
  • 2021-01-22 16:36

    The library Microsoft.Build.Evaluation, which is, I believe, the successor of Roslyn does have this feature, but it is not easy to find.

    I use the code below to obtain the default namespace.

    My tests have shown that it matches the RootNamespace, stored in the .csproj file.

            private string GetDefaultNamespace(Microsoft.Build.Evaluation.Project p)
        {
            string rtnVal = "UNKNOWN_NAMESPACE";
    
            foreach (ProjectItemDefinition def in p.ItemDefinitions.Values)
            {
                if (def.ItemType == "ProjectReference")
                {
                    foreach(ProjectProperty prop in def.Project.AllEvaluatedProperties){
                        if(prop.Name == "RootNamespace"){
                            rtnVal = prop.EvaluatedValue;
                        }
                    }
                }
            }
    
            return rtnVal;
        }
    
    0 讨论(0)
提交回复
热议问题