Haz*_*zza 4 c# visual-studio envdte
我正在为 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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当它找到匹配的类以确保它在我的项目中时,我必须检查命名空间。这感觉就像我在做很多不必要的工作。这是他们使用脚手架模板 Visual Studio 项目给出的示例:
ICodeTypeService codeTypeService = (ICodeTypeService)Context
.ServiceProvider.GetService(typeof(ICodeTypeService));
return codeTypeService
.GetAllCodeTypes(Context.ActiveProject)
.Where(codeType => codeType.IsValidWebProjectEntityType())
.Select(codeType => new ModelType(codeType));
Run Code Online (Sandbox Code Playgroud)
codetypeservice 是正确的方法吗?
编辑 基本上,当它搜索类时,它不仅会在当前活动的项目中进行搜索,还会搜索所有引用的项目。这就是为什么我必须检查命名空间,以便我只能从活动项目中获取结果。我认为这就是它被放慢的原因,因为引用的项目非常大,所以它做了很多完全不必要的工作......
我注意到有人提出了这个问题,提醒我发布我如何让它更快地工作。正如 Maslow 所指出的,Roslyn 很酷,但是当我构建这个扩展时 Roslyn 不可用,除了在预览中,所以基本上它毫无意义。
我的扩展在 GitHub 上,这是一个相关的代码片段:https : //github.com/Hazzamanic/orchardizer/blob/master/Orchardization/UI/CustomViewModel.cs
但是,如果 GitHub 死了/有人为我的代码支付了 100 万美元,这里是相关代码...
/// <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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
拥有所有项目项后,您可以按它们进行过滤。这在相当大的项目中似乎工作得很好,尽管公平地说我真的没有任何大规模的项目。就我而言,我想找到所有具有基类的类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);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1473 次 |
| 最近记录: |