参考:https://www.runoob.com/csharp/csharp-attribute.html

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

[AttributeUsage(validon,AllowMultiple=allowmultiple,Inherited=inherited
)]

直接上一个例子!用于验证属性的特性

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Text.RegularExpressions;public class RegexMailAttribute : AbstractAtrribute
{public override bool IsValidata(object oValue){isValidata = IsEmail(oValue.ToString());ShowLog(oValue);return isValidata;}bool IsEmail(string inputData){Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");return RegEmail.Match(inputData).Success;}}public class RegexNumberAttribute : AbstractAtrribute
{public override bool IsValidata(object oValue){int result = 0;if(int.TryParse(oValue.ToString(), out result)){isValidata = result > 0;}else{Debug.LogError("转换错误:"+oValue);isValidata = false;}ShowLog(oValue);return isValidata;}}public class LongValidateAttribute : AbstractAtrribute
{private long _lMin = 0;private long _lMax = 0;public LongValidateAttribute(long lMin, long lMax){this._lMin = lMin;this._lMax = lMax;}public override bool IsValidata(object oValue){isValidata = this._lMin < (long)oValue && (long)oValue < this._lMax;ShowLog(oValue);return isValidata;}}public abstract class AbstractAtrribute : Attribute
{private Text tipText;public bool isValidata;public abstract bool IsValidata(object oValue);public virtual void SetTipText(Text tipText){this.tipText = tipText;}public virtual void ShowLog(object oValue, Action<string> onSuccess = null, Action<string> onFail = null){string log = "";if (isValidata){log = GetType() + "输入正确:" + oValue.ToString();Debug.Log(log);onSuccess?.Invoke(log);tipText.color = Color.green;}else{log = GetType() + "格式错误:" + (string.IsNullOrEmpty(oValue.ToString()) ? "NULL" : oValue.ToString());Debug.LogError(log);onFail?.Invoke(log);tipText.color = Color.red;}tipText.text = log;}
}public class DataValidate
{public static bool IsValidate<T>(T t, Text[] tipText){bool isValidate = true;Type type = t.GetType();var properties = type.GetProperties();for (int i = 0; i < properties.Length; i++){if(i < tipText.Length){var proper = properties[i];if (proper.IsDefined(typeof(AbstractAtrribute), true)){object item = proper.GetCustomAttributes(typeof(AbstractAtrribute), true)[0];AbstractAtrribute abstractAtrribute = item as AbstractAtrribute;abstractAtrribute.SetTipText(tipText[i]);if (!abstractAtrribute.IsValidata(proper.GetValue(t))){isValidate = false;}}}}return isValidate;}}

注意点:必写 { get; set; }!!!否则读取不到特性

 public class Student{[RegexNumber]public string ID { get; set; }[LongValidate(1000, 99999999999)]public long QQ { get; set; }[RegexMail]public string Mail { get; set; }[RegexNumber]public string Sex { get; set; }}

使用方法

 DataValidate.IsValidate(new Student() { id = id, mail = mail, QQ = testQQ });

测试

        testId = "";testMail = "";testQQ = 0;inputFields[0].onEndEdit.AddListener(OnEndIDMail);inputFields[1].onEndEdit.AddListener(OnEndQQMail);inputFields[2].onEndEdit.AddListener(OnEndEditMail);commitBtn.onClick.AddListener(() => {if(DataValidate.IsValidate(new Student() { id = testId, mail = testMail, QQ = testQQ }, tips)){Debug.Log("全对!!可以提交了");}});

效果:

示例2

// A custom attribute to allow multiple authors per method.
[AttributeUsage(AttributeTargets.Method)]
public class AuthorsAttribute : Attribute
{protected List<string> _authors;public AuthorsAttribute(params string[] names){_authors = new List<string>(names);}public List<string> Authors{get { return _authors; }}// Determine if the object is a match to this one.public override bool Match(object obj){// Return false if obj is null or not an AuthorsAttribute.AuthorsAttribute authors2 = obj as AuthorsAttribute;if (authors2 == null) return false;// Return true if obj and this instance are the same object reference.if (Object.ReferenceEquals(this, authors2))return true;// Return false if obj and this instance have different numbers of authorsif (_authors.Count != authors2._authors.Count)return false;bool matches = false;foreach (var author in _authors){for (int ctr = 0; ctr < authors2._authors.Count; ctr++){if (author == authors2._authors[ctr]){matches = true;break;}if (ctr == authors2._authors.Count){matches = false;}}}return matches;}public override string ToString(){string retval = "";for (int ctr = 0; ctr < _authors.Count; ctr++){retval += $"{_authors[ctr]}{(ctr < _authors.Count - 1 ? ", " : String.Empty)}";}if (retval.Trim().Length == 0){return "<unknown>";}return retval;}
}// Add some authors to methods of a class.
public class TestClass
{[Authors("小王","小张")]public void Method1(){ }[Authors("小李")]public void Method2(){ }[Authors("小王", "小张","小强")]public void Method3(){ }[Authors("小张", "小王")]public void Method4(){ }
}

测试

 // Get the type for TestClass to access its metadata.Type clsType = typeof(TestClass);// Iterate through each method of the class.AuthorsAttribute authors = null;foreach (var method in clsType.GetMethods()){// Check each method for the Authors attribute.AuthorsAttribute authAttr = (AuthorsAttribute)Attribute.GetCustomAttribute(method,typeof(AuthorsAttribute));if (authAttr != null){// Display the authors.Debug.Log($"{clsType.Name}.{method.Name} 开发者: {authAttr}");// Select Method1's authors as the basis for comparison.if (method.Name == "Method1"){authors = authAttr;continue;}// Compare first authors with the authors of this method.if (authors.Match(authAttr)){Debug.Log($"{clsType.Name}.{method.Name} {authors}, {authAttr}  TestClass.Method1 也是相同成员开发的");}// Perform an equality comparison of the two attributes.Debug.Log($"{authors} {(authors.Match(authAttr) ? "相同于" : "不相同于")} {authAttr}");}}

效果

C#之特性(Attribute)相关推荐

  1. .net 特性 Attribute

    public sealed class RemarkAttribute : Attribute{public string Remark { get; set; }// 构造函数public Rema ...

  2. 区分元素特性attribute和对象属性property

    定义 元素特性attribute是指HTML元素标签的特性 下面的id.class.title.a都是特性,其中a叫做自定义特性 <div id="id1" class=&q ...

  3. .NET基础编程之特性 - Attribute

    这一篇文章是给大家介绍的是:.NET基础编程之特性 - Attribute,对这一部分掌握不熟悉的同学,可以仔细的看一下! 一.特性简介 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集. ...

  4. Unity游戏开发——C#特性Attribute与自动化

    这篇文章主要讲一下C#里面Attribute的使用方法及其可能的应用场景. 比如你把玩家的血量.攻击.防御等属性写到枚举里面.然后界面可能有很多地方要根据这个枚举获取属性的描述文本. 比如你做网络框架 ...

  5. 特性Attribute

    1.Attribute介绍    我们用VS进行编程时,智能提示再提供方法和属性列表的时候,有时会有下面的这种情况: 提示某个方法已经是过时的了,还会给与提示信息.出现此效果就是Attribute(特 ...

  6. C#的特性Attribute

    一.什么是特性 特性是用于在运行时传递程序中各种元素(比如类.方法.结构.枚举.组件等)的行为信息的声明性标签,这个标签可以有多个.您可以通过使用特性向程序添加声明性信息.一个声明性标签是通过放置在它 ...

  7. C# 特性 Attribute

    特性就是在类的类名称.属性.方法等上面加一个标记,使这些类.属性.方法等具有某些统一的特征,从而达到某些特殊的需要.举个小栗子:方法的异常捕捉,你是否还在某些可能出现异常的地方(例如数据库的操作.文件 ...

  8. ABP的一些特性 (Attribute)

    大家应该很熟悉Attribute这个东西吧,ABP里面扩展了一些特性,做过滤权限,返回内容等进行控制,在这里小记下,方便后续查看. [DontWrapResult]  //ABP默认对返回结果做了封装 ...

  9. C#的特性(Attribute)详解

    C#特性是指我们可以对类.以及C#程序集中的成员进行进一步的描述,比如我们写一个关于人的类Person,该类可以对人的属性以及某些行为(方法)进行描述.那么如果我们要对人类进行进一步描述呢,比如人这个 ...

  10. 基于特性(Attribute)的实体属性验证方案设计

      各位朋友,我是Payne,大家好,欢迎大家关注我的博客,我的博客地址是https://qinyuanpei.github.io.在这篇文章中,我想和大家探讨下数据校验的相关问题,为什么我会对这个问 ...

最新文章

  1. 2013-2014 ACM-ICPC, NEERC, Southern Subregional Contest Problem D. Grumpy Cat 交互题
  2. sgolayfilt函数_Matlab中Savitzky-Golay filtering(最小二乘平滑滤波)函数sgolayfilt的使用方法...
  3. springmvc 配置 tag lib_Java自学之springMVC:Hello Spring MVC
  4. 【数据结构与算法】实验 编写双链表的结点查找和删除算法
  5. intel 指令集_苹果首款ARM Mac来了,浅谈ARM和Intel处理器
  6. 初用WEB IOU,IE LAB备战启航
  7. 网关 配置内网DNS 服务器
  8. 是时候重估“返利网”的市场价值了
  9. 用计算机弹麻雀,玩麻雀弹
  10. 【编程之外】当遮羞布被掀开,当人们开始接受一切
  11. python start方法_进程方法 run和start的区别
  12. JavaWeb(kuang)
  13. 通信原理眼图画法_四川大学通信原理眼图实验
  14. Caesar Cipher(线段树维护哈希)
  15. 时间差之天数计算Python
  16. 悠哉网李代山与实力派孙红雷有点像
  17. 微软surface屏幕抖动_Microsoft放弃Windows E并显示浏览器投票屏幕
  18. PSpice受控源设置增益参数
  19. 等不到明天了,office2021专业正式版镜像来了
  20. 并发编程5:Java 阻塞队列源码分析(下)

热门文章

  1. 【深度学习】轻量化CNN网络MobileNet系列详解
  2. 历史最全量化交易书籍、视频教程、博客、代码、算法整理
  3. 最全英文停用词表整理(891个)
  4. 移动端-刮刮乐的实现方式
  5. 渲染3d代理文件出现服务器选框,是什么意思?3DMax一渲染就出现这个框框 – 手机爱问...
  6. 掌握 tar 命令让你秒变大牛
  7. photoshopCS5换背景
  8. oracle oaf结构,配置Oracle ebs的oaf开发环境步骤详解
  9. 图解回车和换行的区别
  10. 开源 IM 系统 tinode 部署教程| WSL 环境