c# - 确定 EnvDTE.Project 是否可用

标签 c# .net envdte

我必须经历一个包含不可用项目的大型解决方案。这些不可用的项目不可用,因为它们的路径不再存在。如果这个解决方案要保留这些不可用的引用,是否有一种方法可以确定我正在循环的每个项目是否可用?

下面是一个循环,其目标是确定是否保存了当前解决方案中的每个 ProjectItem。但是,由于某些项目不可用,我不断收到空引用。

bool isDirty = false;
foreach (Project proj in sln.Projects) //sln is my current solution
{
    if (proj == null) //hoping that might do the trick
        continue;
    foreach (ProjectItem pi in proj.ProjectItems)
    {
        if (pi == null) //hoping that might do the trick
            continue;
        if (!pi.Saved)
        {
            isDirty = true;
            break;
        }
    }
}

最佳答案

您可以用一个简单的 LINQ 重写它操作:

//import the LINQ extensions
using System.Linq;
// some code here;
bool isDirty = sln.Projects.Any(pr => pr.ProjectItems != null && !pr.Saved);

根据 MSDN, _Solution.Projects 属性是 Projects 输入,这是一个 IEnumerable没有泛型,所以你应该使用 OfType<TResult> 扩展方法,像这样:

bool isDirty = sln.Projects.OfType<Project>().Any(pr => pr.ProjectItems != null && !pr.Saved);

来自 MSDN:

This method is one of the few standard query operator methods that can be applied to a collection that has a non-parameterized type, such as an ArrayList. This is because OfType<TResult> extends the type IEnumerable. OfType<TResult> cannot only be applied to collections that are based on the parameterized IEnumerable<T> type, but collections that are based on the non-parameterized IEnumerable type also.

关于c# - 确定 EnvDTE.Project 是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754654/

相关文章:

c# - 如何在 Visual Studio 中以编程方式执行 "Go To Definition"?

c# - XAML 绑定(bind)到复杂值对象

c# - 使用 C# 按创建日期降序获取目录中的文件列表

c# - 执行非查询 : Connection property has not been initialized.

c# - objects.GetObject(i) 比 objects[i] 有什么优势?

c# - 调试器启动时如何附加第二个进程?

c# - 如何从 Visual Studio Package 项目获取当前解决方案名称?

c# - 如何以编程方式从 Excel 单元格拖放到启用拖动的任务 Pane ?

c# - 加载常量的 MSIL 指令

c# - 如何正确取消 Task.WhenAll 并抛出第一个异常?