确定 EnvDTE.Project 是否可用
Determining if a EnvDTE.Project is available
我必须完成一个包含 不可用项目 的大型解决方案。这些不可用的项目不可用,因为它们的路径不再存在。如果这个解决方案要保留这些不可用的引用,是否有办法确定我正在循环的每个项目是否是 available/unavailable?
下面是一个循环,其目标是确定是否保存了当前解决方案中的每个 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
property is a Projects
typed, which is a IEnumerable
without generic, so you should use the 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.
我必须完成一个包含 不可用项目 的大型解决方案。这些不可用的项目不可用,因为它们的路径不再存在。如果这个解决方案要保留这些不可用的引用,是否有办法确定我正在循环的每个项目是否是 available/unavailable?
下面是一个循环,其目标是确定是否保存了当前解决方案中的每个 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
property is a Projects
typed, which is a IEnumerable
without generic, so you should use the 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.