2 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個贊
出于某種原因,當(dāng) LINQ 語法實(shí)際上非常有用并且使意圖非常清晰時,它似乎被避免了。
用 LINQ 語法重寫,以下適用 @DavidG 的優(yōu)點(diǎn)。
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();
}
當(dāng)查詢變得更加復(fù)雜時,例如需要測試整個方法簽名的這個let
(完全公開:我的答案),漸進(jìn)式過濾很容易遵循,并且沿途發(fā)現(xiàn)的事實(shí)在子句中高度可見。

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個贊
通過使用空條件運(yùn)算符并將空檢查作為最后一件事,您可以避免再次獲取自定義屬性:
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 關(guān)注
- 119 瀏覽
添加回答
舉報