我正在为Visual Studio构建脚手架工具,并且需要呈现从某个抽象类派生而来的类的列表,但仅是活动项目中的类。我可以使用它,但是运行Visual Studio需要一些时间来运行代码。
ICodeTypeService codeTypeService = (ICodeTypeService)Context
.ServiceProvider.GetService(typeof(ICodeTypeService));
var types = codeTypeService.GetAllCodeTypes(Context.ActiveProject);
foreach (var type in types)
{
type.
if (type.Kind == vsCMElement.vsCMElementClass)
{
foreach (var d in type.Bases)
{
var dClass = d as CodeClass;
var name = type.Name;
if (dClass.Name == "MyAbstractClass")
{
if (type.Namespace.Name.Contains(Context.ActiveProject.Name))
{
yield return type.Name;
}
}
}
}
}
因此,当它找到匹配的类以确保它在我的项目中时,我必须对名称空间进行检查。感觉好像我在做很多不必要的工作。这是他们通过脚手架模板Visual Studio项目提供的示例:
ICodeTypeService codeTypeService = (ICodeTypeService)Context
.ServiceProvider.GetService(typeof(ICodeTypeService));
return codeTypeService
.GetAllCodeTypes(Context.ActiveProject)
.Where(codeType => codeType.IsValidWebProjectEntityType())
.Select(codeType => new ModelType(codeType));
codetypeservice是正确的方法吗?
编辑基本上,当它搜索类时,它不仅会在当前活动项目中执行此操作,还会搜索所有引用的项目。这就是为什么我必须检查名称空间以便仅从活动项目中获取结果的原因。我认为这就是为什么它会变慢的原因,因为引用的项目很大,所以它正在做很多完全不必要的工作……
我注意到有人赞成这个问题,提醒我发布如何使它更快地工作。正如Maslow所指出的那样,Roslyn很酷,但是当我构建此扩展时,Roslyn不可用,除了在预览中,所以基本上它只是毫无意义的。
我的扩展程序在GitHub上,这是一个相关的代码片段:https : //github.com/Hazzamanic/orchardizer/blob/master/Orchardization/UI/CustomViewModel.cs
但是如果GitHub死了/有人为我的代码付了我一百万美元,这是相关的代码...
/// <summary>
/// Recursively gets all the ProjectItem objects in a list of projectitems from a Project
/// </summary>
/// <param name="projectItems">The project items.</param>
/// <returns></returns>
public IEnumerable<ProjectItem> GetProjectItems(EnvDTE.ProjectItems projectItems)
{
foreach (EnvDTE.ProjectItem item in projectItems)
{
yield return item;
if (item.SubProject != null)
{
foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.SubProject.ProjectItems))
yield return childItem;
}
else
{
foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.ProjectItems))
yield return childItem;
}
}
}
一旦拥有所有项目项,就可以按它们进行筛选。在相当大的项目中,这似乎很好用,尽管我确实没有任何大型项目可以公平地进行。就我而言,我想找到所有带有基类的类DatMigrationImpl
。所以我有这样的代码:
var allClasses = GetProjectItems(Context.ActiveProject.ProjectItems).Where(v => v.Name.Contains(".cs"));
// check for .cs extension on each
foreach (var c in allClasses)
{
var eles = c.FileCodeModel;
if (eles == null)
continue;
foreach (var ele in eles.CodeElements)
{
if (ele is EnvDTE.CodeNamespace)
{
var ns = ele as EnvDTE.CodeNamespace;
// run through classes
foreach (var property in ns.Members)
{
var member = property as CodeType;
if (member == null)
continue;
foreach (var d in member.Bases)
{
var dClass = d as CodeClass;
if (dClass == null)
continue;
var name = member.Name;
if (dClass.Name == "DataMigrationImpl")
{
yield return new Migration(member);
}
}
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句