Reading the default namespace through Roslyn API

≡放荡痞女 提交于 2019-12-13 04:49:52

问题


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 should be possible using Roslyn API but I cannot find how to do that. Thanks in advance for information.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/33774240/roslyn-api-defaultnamespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!