标签 Attribute
在一个类上面放一个标签,可以用来表示一些特定规则,比如某个对象的某个属性不想被json化,那么我们在它头上放个标签就行了,或是做ORM时指定某个Class对应的table名字等。
最后标签是通过反射来调用的,一个类只要继承了微软的Attribute类就可以当标签来使用了.
[AttributeUsage(AttributeTargets.All)]//指定Attribute的使用范围,比如只能在class级别使用 public class Column : Attribute { public Column(string str) { this.str = str; } public string str { get; set; } } //第2个 [AttributeUsage(AttributeTargets.All)] public class Table : Attribute {
public string someData { get; set; } //公开属性还可以直接在标签上面写入 public Table(string str) { this.str = str; } public string str { get; set; } } //2个属性 [Column("class")] [Table("table class", someData = "ggc" )] //someData="ggc"是直接对attribute对象写入值! public class Abc { public string x { get; set; } [Column("attr")] public Int32 y { get; set; } } protected void Page_Load(object sender, EventArgs e) { //通过反射可以调用到这个类型头上的attr Type type = typeof(Abc);
bool isGot = Attribute.IsDefined(type, typeof(Column)); //查看有没有某个Attribute Attribute[] attrs = Attribute.GetCustomAttributes(type); //批量获取 string xy = attrs.First().GetType().Name; //可以查看它的名字来选择想要的,或是看有没有想要的. Column column = (Column)Attribute.GetCustomAttribute(type, typeof(Column)); //强转 Column[] columns = (Column[])Attribute.GetCustomAttributes(type, typeof(Column)); column = columns[0]; string x = column.str; //调用方法或是公开属性等等都可以 //实例化之后也是可以一样拿 Abc a = new Abc(); PropertyInfo info = a.GetType().GetProperty("y"); Column attribute2 = (Column)Attribute.GetCustomAttribute(info, typeof(Column)); string xyz = attribute2.str; }
分类:
ASP.NET
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)