亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

從裝飾屬性中提取屬性數據

從裝飾屬性中提取屬性數據

C#
慕神8447489 2022-10-23 10:12:59
有沒有什么方法可以只選擇properties那些用指定裝飾的Attribute并提取Attribute數據......一次通過?目前我首先進行PropertyInfo過濾,然后獲取屬性數據:屬性數據: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[]然后獲取數據。還有其他更有效的方法嗎?
查看完整描述

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(完全公開:我的答案),漸進式過濾很容易遵循,并且沿途發現的事實在子句中高度可見。



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

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


查看完整回答
反對 回復 2022-10-23
  • 2 回答
  • 0 關注
  • 112 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號