第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從裝飾屬性中提取屬性數(shù)據(jù)

從裝飾屬性中提取屬性數(shù)據(jù)

C#
慕神8447489 2022-10-23 10:12:59
有沒有什么方法可以只選擇properties那些用指定裝飾的Attribute并提取Attribute數(shù)據(jù)......一次通過?目前我首先進(jìn)行PropertyInfo過濾,然后獲取屬性數(shù)據(jù):屬性數(shù)據(jù):public class Weight{    public string Name { get; set; }    public double Value { get; set; }    public Weight(string Name,double Value) {        this.Name = Name;        this.Value = Value;    }}屬性:[AttributeUsage(AttributeTargets.Property)]public class WeightAttribute : Attribute{    public WeightAttribute(double val,[CallerMemberName]string Name=null)    {        this.Weight = new Weight(Name, val);    }    public Weight Weight { get; set; }}提取器:private static IReadOnlyList<Weight> ExtractWeights(Type type){    var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)        .Where(x => x.GetCustomAttribute<WeightAttribute>() != null);    var weights = properties        .Select(x => x.GetCustomAttribute<WeightAttribute>().Weight)        .ToArray();    return weights;}正如您在我的Extractor方法中看到的那樣,我首先過濾PropertyInfo[]然后獲取數(shù)據(jù)。還有其他更有效的方法嗎?
查看完整描述

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í)在子句中高度可見。



查看完整回答
反對 回復(fù) 2022-10-23
?
慕無忌1623718

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


查看完整回答
反對 回復(fù) 2022-10-23
  • 2 回答
  • 0 關(guān)注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號