从装饰属性中提取属性数据

有没有什么方法可以只选择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[]然后获取数据。还有其他更有效的方法吗?


慕神8447489
浏览 125回答 2
2回答

汪汪一只猫

出于某种原因,当 LINQ 语法实际上非常有用并且使意图非常清晰时,它似乎被避免了。用 LINQ 语法重写,以下适用 @DavidG 的优点。private static IReadOnlyList<Weight> ExtractWeights(Type type){&nbsp; &nbsp; return (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let attr = p.GetCustomAttribute<WeightAttribute>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where attr != null&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select attr.Weight).ToArray();}当查询变得更加复杂时,例如需要测试整个方法签名的这个let(完全公开:我的答案),渐进式过滤很容易遵循,并且沿途发现的事实在子句中高度可见。

慕无忌1623718

通过使用空条件运算符并将空检查作为最后一件事,您可以避免再次获取自定义属性:private static IReadOnlyList<Weight> ExtractWeights(Type type){&nbsp; &nbsp; return type&nbsp; &nbsp; &nbsp; &nbsp; .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)&nbsp; &nbsp; &nbsp; &nbsp; .Select(x => x.GetCustomAttribute<WeightAttribute>()?.Weight)&nbsp; &nbsp; &nbsp; &nbsp; .Where(x => x!= null)&nbsp; &nbsp; &nbsp; &nbsp; .ToArray();}完整示例:https ://dotnetfiddle.net/fbp50c
打开App,查看更多内容
随时随地看视频慕课网APP