首页 > 编程语言 >C#属性(Attribute)用法实例解析

C#属性(Attribute)用法实例解析

时间:2023-04-12 13:55:43浏览次数:37  
标签:string 自定义 C# Attribute TestAttribute 实例 var public

属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变。本文就以实例形式分析了C#中属性的应用。具体如下:

一、运用范围

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute

[AttributeUsage(AttributeTargets.All)]
  public class TestAttribute : Attribute
  {
  }
  [TestAttribute]//结构
  public struct TestStruct { }
   
  [TestAttribute]//枚举
  public enum TestEnum { }
 
 
  [TestAttribute]//类上
  public class TestClass
  {
    [TestAttribute]
    public TestClass() { }
     
    [TestAttribute]//字段
    private string _testField;
 
    [TestAttribute]//属性
    public string TestProperty { get; set; }
 
    [TestAttribute]//方法上
    [return: TestAttribute]//定义返回值的写法
    public string TestMethod([TestAttribute] string testParam)//参数上
    {
      throw new NotImplementedException();
    }
  }

 这里我们给出了除了程序集和模块以外的常用的Atrribute的定义。

二、自定义Attribute

为了符合“公共语言规范(CLS)”的要求,所有的自定义的Attribute都必须继承System.Attribute。

第一步:自定义一个检查字符串长度的Attribute

[AttributeUsage(AttributeTargets.Property)]     
public class StringLengthAttribute : Attribute
{
  private int _maximumLength;
  public StringLengthAttribute(int maximumLength)
  {
    _maximumLength = maximumLength;
  }
 
  public int MaximumLength
  {
    get { return _maximumLength; }
  }
}

AttributeUsage这个系统提供的一个Attribute,作用来限定自定义的Attribute作用域,这里我们只允许这个Attribute运用在Property上,内建一个带参的构造器,让外部传入要求的最大长度。

第二步:创建一个实体类来运行我们自定义的属性

public class People
{
  [StringLength(8)]
  public string Name { get; set; }
 
  [StringLength(15)]
  public string Description { get; set; }
}

 

 定义了两个字符串字段Name和Description, Name要求最大长度为8个,Description要求最大长度为15.

第三步:创建验证的类

public class ValidationModel
{
 
  public void Validate(object obj)
  {
    var t = obj.GetType();
 
    //由于我们只在Property设置了Attibute,所以先获取Property
    var properties = t.GetProperties();
    foreach (var property in properties)
    {
 
      //这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用if elseif去链接
      //会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。
      if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue;
 
      var attributes = property.GetCustomAttributes();
      foreach (var attribute in attributes)
      {
        //这里的MaximumLength 最好用常量去做
        var maxinumLength = (int)attribute.GetType().
          GetProperty("MaximumLength").
          GetValue(attribute);
 
        //获取属性的值
        var propertyValue = property.GetValue(obj) as string;
        if (propertyValue == null)
          throw new Exception("exception info");//这里可以自定义,也可以用具体系统异常类
 
        if (propertyValue.Length > maxinumLength)
          throw new Exception(string.Format("属性{0}的值{1}的长度超过了{2}", property.Name, propertyValue, maxinumLength));
      }
    }
 
  }
}

这里用到了反射,因为Attribute一般都会和反射一起使用,这里验证了字符串长度是否超过所要求的,如果超过了则会抛出异常

private static void Main(string[] args)
{
    var people = new People()
    {
      Name = "qweasdzxcasdqweasdzxc",
      Description = "description"
    };
    try
    {
      new ValidationModel().Validate(people);
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

原文链接:https://www.cnblogs.com/ldyblogs/p/attribute.html

标签:string,自定义,C#,Attribute,TestAttribute,实例,var,public
From: https://www.cnblogs.com/ZhongXingxing/p/17309559.html

相关文章

  • 16-springcloud-ribbon-2-ribbon实现服务调用
    1、首先加入ribbon的依赖,但是eureka已经依赖了ribbon,所以这里不需要再引用ribbon的依赖;2、要使用ribbon,只需要一个注解: @Bean@LoadBalancedpublic RestTemplaterestTemplate(){    RestTemplaterestTemplate=new RestTemplate();    return restTemplate;}在R......
  • MySQL 中的 distinct 和 group by 哪个效率更高?
     1、distinct用法 语法:SELECTDISTINCTcolumnsFROMtable_nameWHEREwhere_conditions;举例:   多列去重:distinct多列的去重,则是根据指定的去重的列信息来进行,即只有所有指定的列信息都相同,才会被认为是重复的信息。    2、groupby用法  语法:SE......
  • 记录下Mac下制作icns图标的流程
    创建一个文件夹必须要以iconset为后缀mkdirhgl_pngpic.iconset使用sips命令生成10张小图sips-z1616$hgl--outhgl_pngpic.iconset/icon_16x16.pngsips-z3232$hgl--outhgl_pngpic.iconset/[email protected]$hgl--outhgl_pngpic.iconset/icon......
  • 3线性部分:古典解-Schauder理论(严格椭圆算子的Schauder估计)
    严格椭圆算子的Schauder内估计目录严格椭圆算子的Schauder内估计1.齐次方程的内估计2.Schauder内估计2.1:预备知识2.2:Schauder内估计2.3:推论1.齐次方程的内估计本节我们研究一般线性算子的内估计:\[\begin{equation*} Lu=a^{ij}(x)D_{ij}u+b^i(x)D_iu+c(x)u=f(x),a^{ij}=a^......
  • Can't open dsw file in Visual Studio C++ 6.0
    Can'topendswfileinVisualStudioC++6.0 WhenItryto"OpenWorkplace"ofmyproject,visualstudiodoesnothing,solutionexplorerisempty.AlsowhenItrytoopenmyproject,Ioccasionallyseethiserror:Thismakefilewas......
  • UVa 10049 Self-describing Sequence (自描述序列&二分递推)
    10049-Self-describingSequenceTimelimit:3.000secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=34&page=show_problem&problem=990SolomonGolomb's self­describingsequence  istheonlynon­decreas......
  • UVa 11044 Searching for Nessy (water ver.)
    11044-SearchingforNessyTimelimit:3.000secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=99&page=show_problem&problem=1985TheLochNessMonsterisamysteriousandunidentifiedanimalsaidtoinhabi......
  • UVa 253 Cube painting (模拟)
    253-CubepaintingTimelimit:3.000secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=99&page=show_problem&problem=189Wehaveamachineforpaintingcubes.Itissuppliedwiththreedifferentcolors:bl......
  • UVa 103 Stacking Boxes (DP&DAG)
    103-StackingBoxesTimelimit:3.000secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=114&page=show_problem&problem=39BackgroundSomeconceptsinMathematicsandComputerSciencearesimpleinoneortw......
  • UVa 11129 An antiarithmetic permutation (构造题&想法题&分治)
    11129-AnantiarithmeticpermutationTimelimit:3.000secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=2070Apermutationof n+1 isabijectivefunctionoftheinitial n+1......