我必须经历一个包含不可用项目的大型解决方案。这些不可用的项目不可用,因为它们的路径不再存在。如果这个解决方案要保留这些不可用的引用,是否有一种方法可以确定我正在循环的每个项目是否可用?
下面是一个循环,其目标是确定是否保存了当前解决方案中的每个 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 becauseOfType<TResult>
extends the typeIEnumerable
.OfType<TResult>
cannot only be applied to collections that are based on the parameterizedIEnumerable<T>
type, but collections that are based on the non-parameterizedIEnumerable
type also.
关于c# - 确定 EnvDTE.Project 是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754654/