首页 > 编程语言 >C#中特性的使用

C#中特性的使用

时间:2022-08-17 20:35:27浏览次数:43  
标签:string C# 特性 class TestAttribute 使用 type public

一、简介

记录一下特性的使用方法,特性其实就是一个特殊的类,需要继承Attribute,当我们序列化一个对象时,就需要在其类上标注Serializable,这个就是官方提供的一种特性

二、使用

2.1 定义

[AttributeUsage(AttributeTargets.All)]//约束特性使用范围
public class TestAttribute:Attribute//自定义特性类需要继承于Attribute
{
    
}

2.2 特性类的特点

特性类与普通类相似,可以包含属性,字段,方法等

[AttributeUsage(AttributeTargets.All)]//约束特性使用范围
public class TestAttribute:Attribute//自定义特性类需要继承于Attribute
{
    public int TestProp { get; set; }
    public string TestField;
    
    public void Show()
    {
        Console.WriteLine("特性中的方法");
    }
}     

2.3 使用特性标记

[TestAttribute(TestProp = 11,TestField = "字段")]
public class Test
{
    public string Name { get; set; }
}

2.4 标记好特性之后应该怎么用呢

Test test = new Test();
Type type = test.GetType();
if(type.IsDefined(typeof(TestAttribute), true))//是否被TestAttribute标记,包括它的父类被标记也算
{
    object[] attr = type.GetCustomAttributes(typeof(TestAttribute), true);//获取标记该类型的所有TestAttribute特性
    foreach (TestAttribute attribute in attr )//遍历所有的TestAttribute 特性
    {
          int prop =  attribute.TestProp;
          string fie = attribute.TestField;
          attribute.Show();      
    }
    
}    

2.5 拿到了之后又有什么用呢

 目前我只用到了导出数据到excel时,标注其列名

[AttributeUsage(AttributeTargets.Property)]
public class TitleAttibute : Attribute
{
    public string Title;
}
public class Order
{
  private string _date;
  [TitleAttibute(Title = "订单创建日期")]
  public string Date
  {
    get { return _date; }
    set { _date = value; }
  }
  private string _shift;   [TitleAttibute(Title = "班次")]   public string Shift   {     get { return _shift; }     set { _shift = value;}   } }

导出数据时

Type type = obj.GetType();
List<PropertyInfo> propList = type.GetProperties().
                    Where(c => c.IsDefined(typeof(TitleAttibute), true)).ToList();//找被标记的属性
for (int i = 0; i < propList.Count; i++)//遍历所有被标记的属性,
{
    TitleAttibute properAttribute = propList[i].
                        GetCustomAttribute<TitleAttibute>();
    ICell cell = titleRow.CreateCell(i);
    cell.SetCellValue(properAttribute.Title);//设置列名为标记值
 }

2.6 在学习过程中,看到了其他的用法,比如做数据验证,结合反射,功能更加强大

[AttributeUsage(AttributeTargets.Property)]
public class DeviceAttribute : Attribute
{
  public int DeviceIdLen { get; set; }

  public bool Validate(string deviceid)
  {
    return deviceid!= null && deviceid.Lenght == DeviceIdLen ;
  }
}

该特性用于检测要上传数据库的资产编号长度是否符合要求

public class ModelInfo
{    
  [DeviceAttribute(DeviceIdLen = 22)]
  public string DeviceId{ get; set; }
}
public static class DataCheck
{
  public static bool Validate<T>(this T t) where T : class
  {
    Type type = t.GetType();
    foreach (var prop in type.GetProperties())
    {
      if (prop.IsDefined(typeof(DeviceAttribute ), true)) 
      {
        object obj= prop.GetValue(t);
        foreach (DeviceAttribute attribute in prop.GetCustomAttributes(typeof(DeviceAttribute ), true))
        {
          if(!attribute.Validate(obj))
          {
            return false;
          }
        }
      }
    }
    return true;
  }
}

调用扩展方法验证数据合格性

ModelInfo mo = new();
mo.DeviceId = "20120810153131513";
bool isOk = mo.Validate();

标签:string,C#,特性,class,TestAttribute,使用,type,public
From: https://www.cnblogs.com/just-like/p/16596556.html

相关文章

  • 8.使用注解开发
    ......
  • 谷粒商城(无CURD代码)
    GUIGU-GULIMALL项目:写在开头:这份笔记仅仅记录了一些环境搭建以及基础篇中一些技术的使用,基本的CURD大部分没有记录,参考了很多网友的博客。若有冒犯,请联系我删除。参考......
  • tomcat
    1.tomcat简介Tomcat是Apache软件基金会(ApacheSoftwareFoundation)的Jakarta项目中的一个核心项目,由Apache、Sun和其他一些公司及个人共同开发而成。由于有了Sun的......
  • MockJs
    MockJs一、为什么使用mockjs在做开发时,当后端的接口还未完成,前端为了不影响工作效率,手动模拟后端接口。1.我们可以使用json文件来模拟后台数据,但比较局限,无法模拟数据......
  • C#异步编程
    一直不是太懂,唉使用Async和Await的任务异步编程(TAP)模型(C#)|MicrosoftDocsC#彻底搞懂async/await-五维思考-博客园(cnblogs.com)C#之Async/Await-......
  • 夜神模拟器 adb devices 找不到设备
    不要使用AndroidSDK中的adb,删除原先的AndroidSDK环境变量。添加夜神模拟器的环境变量......
  • Canal 数据同步 到 Kafka Canal 配置2
    配置canalvim/opt/module/canal/conf/canal.properties##########################################################commonargument###############......
  • construct
    construe[fromLatin,'toconstruct',fromcom-+struere'tobuild']understandaremarkoractioninaparticularway树立(establish;setup;build)理念/观......
  • leetcode45-跳跃游戏 II
    跳跃游戏II前向dp对于一个数i,从0到i-1进行遍历,如果在这个位置能跳跃到i,那么对i的dp值进行更新。这种方式时间复杂度为O(n^2),效率很低classSolution{publici......
  • 【Azure 事件中心】从Azure Event Hub中消费数据,如何查看当前消费客户端消费数据的Off
    问题描述当通过AzureEventHubSDK消费EventHub中的消息时,必须指定一个StorageAccount(存储账号)用于保存Checkpoint(检查点)。 比如在C#代码中,需要指定StorageAc......