2 回答

TA貢獻1898條經驗 獲得超8個贊
出于某種原因,當 LINQ 語法實際上非常有用并且使意圖非常清晰時,它似乎被避免了。
用 LINQ 語法重寫,以下適用 @DavidG 的優點。
private static IReadOnlyList<Weight> ExtractWeights(Type type)
{
return (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
let attr = p.GetCustomAttribute<WeightAttribute>()
where attr != null
select attr.Weight).ToArray();
}
當查詢變得更加復雜時,例如需要測試整個方法簽名的這個let
(完全公開:我的答案),漸進式過濾很容易遵循,并且沿途發現的事實在子句中高度可見。

TA貢獻1744條經驗 獲得超4個贊
通過使用空條件運算符并將空檢查作為最后一件事,您可以避免再次獲取自定義屬性:
private static IReadOnlyList<Weight> ExtractWeights(Type type)
{
return type
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
.Select(x => x.GetCustomAttribute<WeightAttribute>()?.Weight)
.Where(x => x!= null)
.ToArray();
}
完整示例:https ://dotnetfiddle.net/fbp50c
- 2 回答
- 0 關注
- 112 瀏覽
添加回答
舉報