此LINQ查询表达式因Win32Exception而失败" 访问被拒绝":
Process.GetProcesses().Select(p => p.MainModule.FileName)
这会因IOException而失败" 设备未就绪":
DriveInfo.GetDrives().Select(d => d.VolumeLabel)
过滤掉无法访问的对象并避免异常的最佳方法是什么?
答案 0 :(得分:13)
写一个扩展方法!
void Main()
{
var volumeLabels =
DriveInfo
.GetDrives()
.SelectSafe(dr => dr.VolumeLabel);
}
// Define other methods and classes here
public static class LinqExtensions
{
public static IEnumerable<T2> SelectSafe<T,T2>(this IEnumerable<T> source, Func<T,T2> selector)
{
foreach (var item in source)
{
T2 value = default(T2);
try
{
value = selector(item);
}
catch
{
continue;
}
yield return value;
}
}
}
通过这种方式,您可以自定义您想要的任何行为,并且您不必在where子句中创建笨重的hacky,这样,如果有异常,您甚至可以让它返回替代值。
答案 1 :(得分:10)
根据评论进行更新:此解决方案不适用于常见的枚举器。它确实基于问题示例中使用的枚举器。因此,它不是通用的解决方案。因为它是作为通用解决方案编写的,所以我建议不要使用它(为了简单起见)。我将保留这个答案,以丰富知识库。
另一种扩展方法解决方案。为什么我比现有的解决方案更喜欢它?
Select
和try/catch
的问题。Select
。Skip
和SkipWhile
方法。用法:
var result = DriveInfo
.GetDrives()
.Select(d => d.VolumeLabel)
.SkipExceptions() // Our extension method
.ToList();
代码:
public static class EnumerableExt
{
// We use the `Skip` name because its implied behaviour equals the `Skip` and `SkipWhile` implementations
public static IEnumerable<TSource> SkipExceptions<TSource>(this IEnumerable<TSource> source)
{
// We use the enumerator to be able to catch exceptions when enumerating the source
using (var enumerator = source.GetEnumerator())
{
// We use a true loop with a break because enumerator.MoveNext can throw the Exception we need to handle
while (true)
{
var exceptionCaught = false;
var currentElement = default(TSource);
try
{
if (!enumerator.MoveNext())
{
// We've finished enumerating. Break to exit the while loop
break;
}
currentElement = enumerator.Current;
}
catch
{
// Ignore this exception and skip this item.
exceptionCaught = true;
}
// Skip this item if we caught an exception. Otherwise return the current element.
if (exceptionCaught) continue;
yield return currentElement;
}
}
}
}
答案 2 :(得分:7)
你的回答是正确的。您当然可以尝试在扩展方法中隐藏检查逻辑。
public static IEnumerable<TElement> WhereSafe<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
foreach (var element in sequence)
{
try { selector(element); }
catch { continue; }
yield return element;
}
}
Process
.GetProcesses()
.WhereSafe(p => p.MainModule)
.Select(p => p.MainModule.FileName)
或者更好:
public static IEnumerable<TInner> TrySelect<TElement, TInner>(this IEnumerable<TElement> sequence, Func<TElement, TInner> selector)
{
TInner current = default(TInner);
foreach (var element in sequence)
{
try { current = selector(element); }
catch { continue; }
yield return current;
}
}
Process
.GetProcesses()
.TrySelect(p => p.MainModule.FileName)
答案 3 :(得分:5)
使用以下命令插入WHERE过滤器(尝试访问任何对象并吸收可能的访问错误):
{ try { var x = obj.MyProp; return true; } catch { return false; } }:
第一个表达:
Process
.GetProcesses()
.Where(p => { try { var x = p.MainModule; return true; } catch { return false; } })
.Select(p => p.MainModule.FileName)
第二个表达:
DriveInfo
.GetDrives()
.Where(d => { try { var x = d.VolumeLabel; return true; } catch { return false; } })
.Select(d => d.VolumeLabel)
答案 4 :(得分:2)
我会尝试第一种情况:
//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Process.GetProcesses()
.Where(p => {
try {
var x = p.MainModule;
return true;
}
catch(Win32Exception e2)
{ IgnoreError(); }
})
.Select(p => p.MainModule.FileName)
public static void IgnoreError(Exception e)
{
#if DEBUG
throw e2;
//Save the error track, I prefer log4net
_log.Info("Something bad happened!");
#end if
}
对于第二种情况,我宁愿使用IF并保存日志:
//Somewhere in the begging of your class, in a place whose name I do not care to remember ...
//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public List<string> VolumenLabels()
{
//Return the List<T>
List<string> myVolumeLabels = new List<string>();
//Getting the info
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach(DriveInfo drive in allDrives)
{
if (drive.IsReady == true)
{
myVolumeLabels.Add(drive.VolumeLabel.ToString());
}
else
{
_log.Info("Check the Drive: " + drive.Name + " the device is not ready.");
}
}
return myVolumeLabels;
}
我希望,我帮了一下......祝你有愉快的一天!