栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用反射按声明顺序获取属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用反射按声明顺序获取属性

在.net 4.5 (甚至vs2012中的.net
4.0)上,
您可以使用带有

[CallerLineNumber]
属性的巧妙技巧来进行反射操作,从而使编译器为您的属性插入顺序更好:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]public sealed class OrderAttribute : Attribute{    private readonly int order_;    public OrderAttribute([CallerLineNumber]int order = 0)    {        order_ = order;    }    public int Order { get { return order_; } }}public class Test{    //This sets order_ field to current line number    [Order]    public int Property2 { get; set; }    //This sets order_ field to current line number    [Order]    public int Property1 { get; set; }}

然后使用反射:

var properties = from property in typeof(Test).GetProperties()      where Attribute.IsDefined(property, typeof(OrderAttribute))      orderby ((OrderAttribute)property     .GetCustomAttributes(typeof(OrderAttribute), false)     .Single()).Order      select property;foreach (var property in properties){   //}

如果必须处理部分类,则可以使用来对属性进行附加排序

[CallerFilePath]



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576312.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号