AttributeUsage属性

合集下载

序列化和反序列化的几种方式(DataContractSerializer)(二)

序列化和反序列化的几种方式(DataContractSerializer)(二)

序列化和反序列化的⼏种⽅式(DataContractSerializer)(⼆)DataContractSerializer 类使⽤提供的数据协定,将类型实例序列化和反序列化为 XML 流或⽂档。

⽆法继承此类。

命名空间: System.Runtime.Serialization程序集: System.Runtime.Serialization(在 System.Runtime.Serialization.dll 中)备注使⽤ DataContractSerializer 类可以将类型实例序列化和反序列化为 XML 流或⽂档。

通过将 DataContractAttribute 特性应⽤于类,⽽将DataMemberAttribute 特性应⽤于类成员,可以指定要序列化的属性和字段。

从字⾯意思来理解就是:数据契约序列化,本⽂主要是讲解⽤DataContractSerializer 序列化和反序列化,关于它在WCF中的应⽤⼤家可以参考《WCF全⾯解析上册蒋⾦楠著》第五章序列化,⾥⾯有专门的介绍。

DataContractAttribute与DataMenmberAttribute1#region程序集 System.Runtime.Serialization.dll, v4.0.0.02// C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Runtime.Serialization.dll3#endregion45using System;67namespace System.Runtime.Serialization8 {9// 摘要:10// 指定该类型要定义或实现⼀个数据协定,并可由序列化程序(如 System.Runtime.Serialization.DataContractSerializer)进⾏序列化。

属性文法的名词解释

属性文法的名词解释

属性文法的名词解释属性文法(Attribute Grammar)是一种形式化的文法,用于描述计算机程序中的语法结构和语义信息之间的关系。

它是上下文无关文法(Context-Free Grammar)的扩展,引入了属性(Attribute)的概念,用于描述语法结构的特性和语义信息的传递。

属性文法的定义包括两个部分:语法规则和属性定义。

语法规则描述了语法结构的产生方式,属性定义则指定了每个语法结构的属性计算方式。

在属性文法中,语法结构可以是终结符、非终结符和属性。

终结符是语法中不可再分的最基本元素,例如数字、运算符等。

非终结符定义了可扩展的语法结构,例如表达式、语句等。

属性则用于描述语法结构的特性。

一个语法结构可以有多个属性,例如,一个表达式可以包含属性值、数据类型等。

属性文法中的语法规则由产生式表示。

产生式(Production)定义了从一个语法结构生成另一个语法结构的方式。

每个产生式都有一个左部和右部。

左部是一个非终结符,右部是由终结符、非终结符和属性组成的序列。

产生式的右部可以包含语义规则,用来计算属性值。

属性文法中的属性定义规定了每个语法结构的属性计算方式。

一个属性可以是综合属性(Synthesized Attribute)或继承属性(Inherited Attribute)。

综合属性定义了由当前语法结构计算的属性值,它的值只依赖于当前语法结构自身和它的子结构。

继承属性定义了由当前语法结构的父结构计算的属性值,它的值依赖于父结构的属性值和兄弟结构的属性值。

在属性文法的计算过程中,首先对终结符和非终结符的属性进行初始化。

然后按照产生式进行属性传递和计算。

属性传递分为自顶向下和自底向上两种方式。

自顶向下传递属性规定了属性值从父结构向子结构计算传递的方式,自底向上传递属性规定了属性值从子结构向父结构计算传递的方式。

属性文法的应用领域广泛。

在编译原理中,属性文法被用于描述语言的语法和语义。

它可以通过属性计算的方式对程序进行语义分析和优化。

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

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

C#属性(Attribute)⽤法实例解析属性(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上,内建⼀个带参的构造器,让外部传⼊要求的最⼤长度。

C#基础知识梳理系列八:定制特性Attribute

C#基础知识梳理系列八:定制特性Attribute

摘要设计类型的时候可以使用各种成员来描述该类型的信息,但有时候我们可能不太愿意将一些附加信息放到类的内部,因为这样,可能会给类型本身的信息描述带来麻烦或误解。

我们想为类型、属性、方法及返回值附加额外的信息,这些附加信息可以更明确的表达类及其对象成员的状态,怎么办?定制特性Attribute可以做到。

为了避免Attribute与Property翻译性误解,我们以下的讨论中将以特性表示Attribute。

细心的读者可能会发现如下类似定义://项目的AssemblyInfo.cs文件内有:[assembly: Guid("df510f85-e549-4999-864d-bb892545690b")][assembly: AssemblyVersion("1.0.0.0")]//也可能会发现有些类前面也有类似的语句:[Serializable, ComVisible(true)]public sealed class String{}//在我们开发WCF项目时,定义接口契约时接口前面也有类似的语句:[ServiceContract]public interface IService{}这些放在方括弧[]中的Serializable、ServiceContract就是.NET Framework提供的特性Attribute。

它们有的作用于程序集,有的作用于类和接口,也有的作用于属性和方法等其他成员。

第一节定制特性Attribute特性Attribute是指给声明性对象附加一些声明性描述信息,这些信息在经过编译器编译后相当于目标对象的自描述信息被编译进托管模块的元数据中,很显然,如果这些描述信息太多,会大大增加元数据的体积,这一点要注意。

编译器只是将这些描述信息编译生成到元数据中,而对Attribute的“逻辑”并不关注。

前面提到的AssemblyVersion 、Serializable、ServiceContrac等都是继承于System.Attribute类,CLS要求定制Attribute必须继承于System.Attribute类,为了符合规范,所有的定制特性都要以Attribute后缀,这只是一个规范,也可以不使用此后缀,并没有强制。

C#自定义特性(Attribute)详解

C#自定义特性(Attribute)详解

C#⾃定义特性(Attribute)详解什么是特性特性的定义:公共语⾔运⾏时允许添加类似关键字的描述声明,叫做attribute,它对程序中的元素进⾏标注,如类型、字段、⽅法、和属性等。

attribute和.NetFramework⽂件的元数据保存在⼀起,可以⽤来在运⾏时描述你的代码,或者在程序运⾏的时候影响应⽤程序的⾏为。

如何编写⾃定义特性为了帮助⼤家理解⾃定义的特性,⾸先带⼤家了解⼀下编译器遇到代码中某个应⽤了⾃定义特性时,是如何处理的,以检验Model为例,假如声明⼀个C#属性,如下public class User{/// <summary>/// 名称/// </summary>public string Name { get; set; }/// <summary>/// 邮箱/// </summary>[EmailAttribute]public string Email { get; set; }/// <summary>/// 薪⽔/// </summary>[LenghtAttribute(10000, 100000)]public decimal Salary { get; set; }}[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = = false, Inherited = false)]public class LenghtAttribute{private int _minLenght = 0;private int _maxLenght = 0;public LenghtAttribute(int minLenght, int maxLenght){_minLenght = minLenght;_maxLenght = maxLenght;}}当编译器发现这个属性应⽤了⼀个FiedlName特性时,先会将字符串Attribute追加到这个名称上,形成⼀个组合名称FieldNameAttribute,然后搜索路径的所有名称空间中搜索有指定该名称的类,但是注意,如果编译器发现了有某个特性标记了数据项,并且该名称为Attribute结尾,编译器不会将该字符加到组合名称中,所以这就是我们⽤特性标注字段是编译器会默认将Attribute字符以浅蓝⾊字体显⽰的原因之后编译器会找到含有该名称的类,且这个类直接或间接派⽣⾃System.Attribute。

Unity3D中的Attribute详解(三)

Unity3D中的Attribute详解(三)

Unity3D中的Attribute详解(三)上⼀篇我们对系统的Attributes进⾏了MSIL代码的查看,了解到了其本质就是⼀个类的构造函数。

本章我们将编写⾃⼰的Attributes。

⾸先我们定义书的属性代码,如下:[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class,AllowMultiple = true,Inherited = false)]class BookAttribute : Attribute{private string bookName;private string bookAuthor;private int bookPrice;public int year = 1990;public int version = 0;public BookAttribute(string bookname,string bookauthor,int bookprice){bookName = bookname;bookAuthor = bookauthor;bookPrice = bookprice;}public string BookName { get { return bookName; } }public string BookAuthor { get { return bookAuthor; } }public int BookPrice { get { return bookPrice; } }}写⾃⼰的Attribute其实⾮常简单,⾸先你的类需要直接或者间接地继承⾃系统类Attribute。

我们查看Attribute类就会发现该类只有两⼤类的⽅法,获取Attribute和IsDefined。

其次,使⽤AttributeUsage这个Attribute,⾮常有意思。

查看AttributeUsage类,发现构造函数的参数只有⼀个AttributeTargets,就是Attribute的限制范围,这是系统定义的枚举,我们稍后再做详解。

C#中的方括号[](特性、属性)

C#中的方括号[](特性、属性)

C#中的⽅括号[](特性、属性)约定:1.”attribute” 和 ”attributes” 均不翻译2.”property” 译为“属性”3.msdn 中的原句不翻译4.”program entity” 译为 ” 语⾔元素 ”Attributes in C#介绍Attributes 是⼀种新的描述信息,我们既可以使⽤ attributes 来定义设计期信息(例如帮助⽂件,⽂档的 URL ),还可以⽤ attributes 定义运⾏时信息(例如,使 XML 中的元素与类的成员字段关联起来)。

我们也可以⽤ attributes 来创建⼀个“⾃描述”的组件。

在这篇指南中我们将明⽩怎么创建属性并将其绑定⾄各种语⾔元素上,另外我们怎样在运⾏时环境下获取到 attributes 的⼀些信息。

定义MSDN 中做如下定义 (ms-help://MS.MSDNQTR.2002APR.1033/csspec/html/vclrfcsh spec_17_2.htm)"An attribute is a piece of additional declarative information that is specified for a declaration."使⽤预定义 Attributes在 c# 中已有⼀⼩组预定义的 attributes ,在我们学习怎样创建⾃定义 attributes 前,先来了解下在我们的代码中使⽤那些预定义的 attributes.1using System;23public class AnyClass45 {6 [Obsolete( " Don't use Old method, use New method " , true )]78static void Old( ) { }910static void New( ) { }1112public static void Main( )13 {14 Old( );15 }16 }仔细看下该实例,在该实例中我们⽤到了 ”Obsolete”attribute ,它标记了⼀个不该再被使⽤的语⾔元素(译者注:这⾥的元素为⽅法),该属性的第⼀个参数是 string 类型,它解释为什么该元素被荒弃,以及我们该使⽤什么元素来代替它。

Attribute在.net编程中的应用(全)

Attribute在.net编程中的应用(全)

Atrribute 的基本概念经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行。

实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握Attribute,以及它的使用方法,特地收集了几个Attribute使用的例子,提供给大家参考。

在具体的演示之前,我想先大致介绍一下Attribute。

我们知道在类的成员中有property成员,二者在中文中都做属性解释,那么它们到底是不是同一个东西呢?从代码上看,明显不同,首先就是它们的在代码中的位置不同,其次就是写法不同(Attribute必须写在一对方括符中)。

什么是Atrribute首先,我们肯定Attribute是一个类,下面是msdn文档对它的描述:公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。

Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。

在.NET中,Attribute被用来处理多种问题,比如序列化、程序的安全特征、防止即时编译器对程序代码进行优化从而代码容易调试等等。

下面,我们先来看几个在.NET中标准的属性的使用,稍后我们再回过头来讨论Attribute这个类本身。

(文中的代码使用C#编写,但同样适用所有基于.NET的所有语言)Attribute作为编译器的指令在C#中存在着一定数量的编译器指令,如:#define DEBUG, #undefine DEBUG, #if等。

这些指令专属于C#,而且在数量上是固定的。

而Attribute用作编译器指令则不受数量限制。

比如下面的三个Attribute:∙Conditional:起条件编译的作用,只有满足条件,才允许编译器对它的代码进行编译。

AttributeUsage属性

AttributeUsage属性

AttributeUsage属性AttributeUsage属性除了定制attributes之外,可以使用Attributes属性定义如何使用这些属性。

例如:[AttributeUsage( validon,AllowMultiple = allowmultiple,Inherited = inherited)]强烈推荐使用AttributeUsage属性将属性文档化,因此属性的用户能直接使用已命名的属性,而不用在源代码中查找公用的读/写字段和属性。

定义属性目标1public enum AttributeTargets2{3Assembly = 0x0001,4Module = 0x0002,5Class = 0x0004,6Struct = 0x0008,7Enum = 0x0010,8Constructor = 0x0020,9Method = 0x0040,10Property = 0x0080,11Field = 0x0100,12Event = 0x0200,13Interface = 0x0400,14Parameter = 0x0800,15Delegate = 0x1000,16All = Assembly │ Module │ Class │ Struct │ Enum │ Constructor │17Method │ Property │ Field │ Event │ Interface │Parameter │18Delegate,1920ClassMembers = Class │ Struct │ Enum │ Constructor │ Method │21Property │ Field │ Event │ Delegate │ Interface,22}23当使用Attribute属性时,能指定AttributeTargets.all(属性目标),因此属性能被附加到在枚举Attribute Targets列出的任意类型上。

C#特性【Attribute】【什么是特性?以及特性的一些修饰】

C#特性【Attribute】【什么是特性?以及特性的一些修饰】

C#特性【Attribute】【什么是特性?以及特性的⼀些修饰】特性【Attribute】是什么?概念:1. 特性AttriBute:就是⼀个类,能直接继承/间接继承⾃AttriBute⽗类;2. 约定俗成⽤Attribute结尾,标记时就可以省略,eg:[CustomAttribute] ---> [Custom];3. 可以⽤中括号包裹,标记到元素,其实就是调⽤构造函数【如果⽗类⽤了带参数的构造函数,特性调⽤只能改为以下结构----> [Custom(0)]】;4. 然后可以指定属性,字段,修饰参数,返回值,但是⽅法不可以;特性⽆处不在,⽐如我们经常⽤在元素上⾯添加的,[ ] 中括号形式的东西,基本上,我们在⼯作中遇到的各种的框架⾥⾯都有eg :EF-MVC-WCF-Webservice-UniTest-IOC-AOP-SuperSocket,如果,添加了[Serializable],就表⽰这个元素可以序列化,那特性究竟是什么呢?我们不妨按F12点进去看看,可以看到这个特性SerializableAttribute就是⼀个类,继承于Attribute抽象类,那我们⾃⼰动⼿写⼀个试试public class CustomAttribute : Attribute{}[CustomAttribute]public class Student{public int Id { get; set; }public string Name { get; set; }public void Study(){Console.WriteLine($"{}");}public string Answer(string name){return $"This is {name}";}}我们同时⼜可以修改为以下格式:说明了什么?说明:⽤Attribute结尾,标记时就可以省略,eg:[CustomAttribute] ---> [Custom]那我们再进⼀步修改试试,继承CustomAttribute类,调⽤看看:public class CustomAttribute : Attribute{}public class CustomAttriButeChild : CustomAttribute{}那我们是不是就可以得到⼀个:【特性AttriBute:就是⼀个类,直接继承/间接继承⾃AttriBute⽗类】的结论那特性既然是⼀个类,那它⾥⾯⼜可以放什么东西呢?1.⽆参构造函数;public class CustomAttribute : Attribute{public CustomAttribute(){Console.WriteLine("这是⼀个⽆参数构造函数");}}public class CustomAttriButeChild : CustomAttribute{}2.int 类型的参数public class CustomAttribute : Attribute{public CustomAttribute(int Id){Console.WriteLine("如果只有当前的这个构造函数,继承当前⽗类的⼦类会报错,why?");}}public class CustomAttriButeChild : CustomAttribute{public CustomAttriButeChild() : base(123){Console.WriteLine("继承⽗类的⼦类报错,因为它继承了⽗类,但是它只有⼀个带参数的构造函数,那么调⽤也必须显⽰指定调⽤");}}3.⽆参,int,string 同时存在的情况呢?public class CustomAttribute : Attribute{public CustomAttribute(){Console.WriteLine("这是⼀个⽆参数构造函数");}public CustomAttribute(int Id){Console.WriteLine("如果只有当前的这个构造函数,继承当前⽗类的⼦类会报错,why?");}public CustomAttribute(string name){Console.WriteLine("string类型的构造函数");}}public class CustomAttriButeChild : CustomAttribute{public CustomAttriButeChild() : base(123){Console.WriteLine("继承⽗类的⼦类报错,因为它继承了⽗类,但是它只有⼀个带参数的构造函数,那么调⽤也必须显⽰的指定调⽤");}}这是分开调⽤特性的情况,那我们⼀起调⽤呢?[Custom(0)]--- [Custom]---[Custom()]上⾯三个分开都可以调⽤,但是如果同时调⽤就会提⽰特性重复,默认情况不允许,那么我怎么可以做到同时使⽤多个特性呢?我们加"[AttributeUsage]"特性试试加上这个[AttributeUsage]特性之后编译器,就没有在显⽰特性重复,是不是说明这个特性影响编译器,我们进去看看它⾥⾯都有些什么元素,AttributeTargets.All,表⽰可以修饰任何⽬标元素,那我们更换⼀个呢?为什么会报错??因为AttributeTargets.Method----->只能⽤来修饰⽅法那我们希望它⼜可以修饰⽅法,⼜可以修饰属性,⼜可以修饰类呢?[AttributeUsage]特性,影响编译器,它能-----指定修饰的对象------能否重复修饰---修饰的特性⼦类是否继承 ---> [AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)]特性还可以指定属性,字段public class CustomAttribute : Attribute{public CustomAttribute(){}public CustomAttribute(string name){}public CustomAttribute(int Id){}public string Remake;public string Description { get; set; }public void Show(){}}同时字段还能修饰参数,返回值///<summary>///特性在⽅法的参数前⾯,⽤来修饰参数的/// [return:Custom]还可以修饰返回值///</summary>[return: Custom]public string Answer([Custom]string name){return $"This is {name}";}特性多重修饰写法:1//⽅法⼀:2 [Custom()]3 [CustomAttriButeChild]4 [Custom(0) ]5 [Custom(0, Remake= "字段")]//构造函数的传递⽅式:是直接传值,字段需要带Remake6 [Custom(0,Remake ="1115",Description = "属性")]1//⽅式⼆:2 [return: Custom, Custom, Custom(0), Custom(0, Remake = "1115", Description = "属性")]那问题来了,看了这么多,特性到底有什么⽤让我们接着往下⾯探讨//程序⼊⼝static void Main(string[] args){Student student = new Student(){Id = 1, Name = "Attribute"};student.Study();student.Answer("");}跟踪发现写了那么多特性根本就没什么⽤,我们⾃定义的特性,看起来好像毫⽆意义的样⼦,那框架提供的特性究竟是怎么产⽣价值的呢??那我们新建⼀个studentVip类反编译看看:public class StudentVip : Student{public string VipGroup { get; set; }public void DoHomeWork(){}}编译结果展⽰:我们加上我们⾃定义的特性反编译试试:[Custom("123",Remake ="VIP",Description ="Hello!")]public class StudentVip : Student{[Custom("123", Remake = "VIP", Description = "Hello!")]public string VipGroup { get; set; }[Custom("123", Remake = "VIP", Description = "Hello!")]public void DoHomeWork(){}}反编译之后得到的结果:反编译之后,发现特性会在元素的内部⽣成.custom的东西,那我们看⼀下框架⾥⾯的特性,加上编译以后⼜有什么变化呢?框架特性也是⼀样,我们C#访问不到,是不是可以理解为特性没有产⽣任何变化,但框架究竟是怎么产⽣功能的呢?也就是怎么在程序运⾏的时候,能够找到特性的呢?---反射我们如何在程序运⾏中⽤反射去找到特性?可以从类型属性⽅法都可以获取特性实例,先IsDefined判断检测,通过反射在构造实例,再获取(实例化)我们新建⼀个InvokeCenter类来看看:public class InvokeCenter{///<summary>///⼀定要先IsDefined判断检测,通过反射在构造实例,再获取///</summary>///<typeparam name="T"></typeparam>///<param name="student"></param>public static void MangerStudent<T>(T student) where T : Student{//打印属性Console.WriteLine($"{student.Id}_{}");student.Study();student.Answer("123");Type type = student.GetType();//检查特性是否存在if (type.IsDefined(typeof(CustomAttribute), true)){//获取列表找出全部,也可以只找⼀个type.GetCustomAttribute--这种⽅式使⽤场景⽐较多Object[] oAttributeArray = type.GetCustomAttributes(typeof(CustomAttribute), true);foreach (CustomAttribute attribute in oAttributeArray){attribute.Show();}//循环所有的属性foreach (var prop in type.GetProperties()){//如果这个属性包含这个特性//那么我们就获取到包含这个特性属性的列表,它是这个数组集合if (type.IsDefined(typeof(CustomAttribute), true)){Object[] OAttributeProp = type.GetCustomAttributes(typeof(CustomAttribute), true);foreach (CustomAttribute attribute in OAttributeProp){attribute.Show();}}}//把所有的⽅法找出来foreach (var method in type.GetMethods()){//判断是否具有特性if (type.IsDefined(typeof(CustomAttribute), true)){Object[] oAttributeMethod = type.GetCustomAttributes(typeof(CustomAttribute), true);foreach (CustomAttribute attribute in oAttributeMethod){attribute.Show();}}}}}}//前⾯我们⾃定义的CustomAttribute特性的部分代码修改[AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)]public class CustomAttribute : Attribute{public CustomAttribute(){Console.WriteLine($"{this.GetType().Name} ⽆参数构造函数执⾏");}public CustomAttribute(string name){Console.WriteLine($"{this.GetType().Name} string参数构造函数执⾏");this._Name = name;}public CustomAttribute(int Id){Console.WriteLine($"{this.GetType().Name} int参数构造函数执⾏");this._Id = Id;}private int _Id = 0;private string _Name = "";public string Remake;public string Description { get; set; }public void Show(){Console.WriteLine($"{this._Id}_{this._Name}_{this.Remake}_{this.Description}");}}//程序⼊⼝调⽤跟踪static void Main(string[] args){{Student student = new StudentVip(){Id = 2, Name = "特性"};InvokeCenter.MangerStudent<Student>(student);}}跟踪的结果展⽰:以及为什么会有对应条数截图的说明:结论:程序运⾏时可以找到特性,那就可以发挥特性的作⽤,提供额外的信息,⾏为,特性本⾝是没有⽤的,需要⼀个第三⽅InvokeCenter,在这⾥主动检测并提供特性,才能提供功能,那么框架的特性⽅式也是⼀样的,框架⾥⾯已经集成完,⾃⼰去检测特性,另外,特性是在编译前就已经确定好了,构造函数/属性/字段,都不能⽤变量【所以MVC5-filter 是不能注⼊的,只有在core⾥⾯才提供了注⼊filter的⽅式】。

.Net试题

.Net试题
dgvData.DataMember = ds.Tables["table1"];
B. dgvData.DataMember = ds;
C. dgvData.DataSource = new DataView(ds.Tables["table1"]);
D. dgvData.DataSource = ds.Tables["table1"];
32. 在 .NET 框架下,使用 组件时发生错误将引发()异常。
A. SqlException B. DataException C. ArgumenException D. IOExption
33. 在 .NET 框架下开发三层架构应用程序时,以下代码最可能出现在()。
A. TreeNode B. int C. string D. TreeView
30. 用户自定义异常类可以从()类继承。
A. Exception B. CustomException C. ApplicationException D .BaseException
If (txtLogInId.Text.Trim()==””){
MessageBox.Show(“请输入用户名”);
Txtloginid.Focus();
}
A. 表现层 B. 业务逻辑层 C. 数据访问层 D. 模型层
34. 使用 Visual Studio 2008 开发并进行单元测试时,断言 Assert.Inconclusive() 方法的作用是()。
21. 已知变量 ds 引用某个 DataSet 对象,该 DataSet 对象中已包含一个表名为“table1”的数据表。在 Windows 窗体 Form1 中,为了将变量名为 dgvData 的 DataGridView 控件绑定到数据表“table1”,可以使用代码()。【选两项】

C#特性的介绍及应用场景

C#特性的介绍及应用场景

C#特性的介绍及应⽤场景1.特性的任务:特性就是为了⽀持对象添加⼀些⾃我描述的信息,不影响类封装的前提添加额外信息。

如果你⽤这个信息,那特性就有⽤;如果你不需要这个信息,那么这个特性就没⽤。

2.特性的基类:Attribute。

例如:Obsolete特性,提出警告信息或错误信息,特性可以影响编译、影响运⾏。

3.特性类通常⽤Attribute结尾,在使⽤的时候可以⽤全称,也可以去掉这个结尾,也可以加上⼩括号显⽰调⽤构造函数,如果不加⼩括号默认调⽤⽆参构造函数,也可以在括号内直接给属性或字段赋值。

4.特性往往只能修饰⼀个对象⼀次,需要设置属性的属性的时候,需要给属性添加AttributeUsage属性,可以⽤来设置:是否允许多次修饰、修饰对象的类别(类or字段等)5.DLL⽂件=IL中间语⾔+metadata元数据,特性信息会被编译到元数据中。

6.使⽤场景6.1为类或成员添加描述信息,然后在使⽤的时候拿到该信息。

///<summary>///描述实体映射的数据表///</summary>public class TableNameAttribute : Attribute{public TableNameAttribute(){}public string TableName { get; set; }}[TableName(TableName = "Users")]public class User{public int Id { get; set; }public string Name { get; set; }}class Program{public static void Main(string[] args){User user = new User();Type t = user.GetType();object[] customAttrs = t.GetCustomAttributes(true);for (int i = 0; i < customAttrs.Length; i++){if (customAttrs[i] is TableNameAttribute){TableNameAttribute tnAttr = (TableNameAttribute)customAttrs[i];Console.WriteLine(tnAttr.TableName);}}}}6.2 做数据验证public class IntValidateAttribute : Attribute{///<summary>///最⼩值///</summary>private int minValue { get; set; }///<summary>///最⼤值///</summary>private int maxValue { get; set; }///<summary>///构造函数///</summary>///<param name="minValue"></param>///<param name="maxValue"></param>public IntValidateAttribute(int minValue, int maxValue){this.minValue = minValue;this.maxValue = maxValue;}///<summary>///检验值是否合法///</summary>///<param name="checkValue"></param>///<returns></returns>public bool Validate(int checkValue)return checkValue >= minValue && checkValue <= maxValue;}}public class User{[IntValidate(1, 10)]public int Id { get; set; }public string Name { get; set; }}public class BaseDal{public static string Insert<T>(T model){Type modelType = typeof(T);//获取类型的所有属性PropertyInfo[] propertyInfos = modelType.GetProperties();bool boIsCheck = true;//循环所有属性foreach (var property in propertyInfos){//获取属性的所有特性object[] attrs = property.GetCustomAttributes(true);if (.ToLower().Contains("int")){foreach (var attr in attrs){if (attr is IntValidateAttribute){IntValidateAttribute intValidate = (IntValidateAttribute)attr;//执⾏特性的验证逻辑boIsCheck = intValidate.Validate((int)property.GetValue(model)); }}}if (!boIsCheck){break;}}if (boIsCheck){return"验证通过,插⼊数据库成功";}else{return"验证失败";}}}class Program{public static void Main(string[] args){string msg = BaseDal.Insert<User>(new User() { Id = 123, Name = "lvcc" }); Console.WriteLine(msg);}}6.3 添加说明信息并获取,同6.1///<summary>///备注特性///</summary>public class RemarkAttribute : Attribute{private string Remark { get; set; }public RemarkAttribute(string Remark){this.Remark = Remark;}public string GetRemark(){return this.Remark;}}public enum ESex{[Attributes.Remark("男的")]boy=1[Attributes.Remark("⼥的")]girl =2}///<summary>///提供扩展⽅法///</summary>public static class EnumExtension{public static string GetRemark(this Enum model){if (model is ESex){Type type = typeof(ESex);FieldInfo fi = type.GetField(model.ToString());object[] attributes = fi.GetCustomAttributes(true);foreach (var attr in attributes){if (attr is RemarkAttribute){RemarkAttribute remark = (RemarkAttribute)attr;return remark.GetRemark();}}}return string.Empty;}}class Program{public static void Main(string[] args){Console.WriteLine(ESex.boy.GetRemark());}}。

c#之Attribute特性的原理

c#之Attribute特性的原理

c#之Attribute特性的原理当我们在Visual Studio添加⼀个⾃定义控件时,它都会给我们以下默认的代码。

[DefaultProperty("Text")][ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]public class WebCustomControl1 : WebControl{[Bindable(true)][Category("Appearance")][DefaultValue("")][Localizable(true)]public string Text{get{String s = (String)ViewState["Text"];return ((s == null) ? String.Empty : s);}set{ViewState["Text"] = value;}}protected override void RenderContents(HtmlTextWriter output){output.Write(Text);}}[DefaultProperty("Text")][ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]public class WebCustomControl1 : WebControl{[Bindable(true)][Category("Appearance")][DefaultValue("")][Localizable(true)]public string Text{get{String s = (String)ViewState["Text"];return ((s == null) ? String.Empty : s);}set{ViewState["Text"] = value;}}protected override void RenderContents(HtmlTextWriter output){output.Write(Text);}}在这个控件中有个默认的属性"Text",在这个属性有[DefaultValue("")]相应的特性,来给该属性设置默认值。

属性的英文名词解释

属性的英文名词解释

属性的英文名词解释属性,在日常生活中,是我们用来描述或归类事物的特征或性质。

它们是我们理解和与世界交互的基础。

在计算机科学和统计学中,属性也扮演着重要的角色。

在本文中,我们将探讨属性的英文名词解释以及属性在不同领域的应用。

一、属性的概念与定义属性(Attribute)是指事物的特征或性质,是描述事物所具有的特征的一个属性、变量或特性。

它可以是事物的外在特征,例如颜色、形状、大小等,也可以是事物的内在特性,例如性格、价值观等。

属性是衡量事物差异并进行分类的基础。

在计算机科学中,属性也可以指代数据对象的特征。

在数据库中,一个属性通常是一个表的列,它描述了每个数据项的特定内容。

例如,一个人的属性可以包括姓名、年龄、性别等。

在机器学习和数据挖掘中,属性则指代用于描述实例的特征。

二、属性的分类属性可以根据其性质和使用方式进行分类。

下面是几种常见的属性分类方式:1. 数值属性(Numeric Attribute):数值属性是指可以以数值形式表示的属性。

它可以是连续的(如身高、体重),也可以是离散的(如年龄段)。

2. 类别属性(Categorical Attribute):类别属性是指具有一个有限集合的值的属性。

例如,性别可以是男、女两个类别,它是一个类别属性。

3. 有序属性(Ordinal Attribute):有序属性是指具有可排序性质的属性。

例如,学生的成绩可以用“A”、“B”、“C”等等表示,这是一个有序属性。

4. 二元属性(Binary Attribute):二元属性是指只有两种取值的属性。

例如,一个人是否结婚,可以用“是”或“否”表示。

5. 时间属性(Temporal Attribute):时间属性是指与时间相关的属性。

例如,日期、时间等。

三、属性在不同领域的应用1. 数据库管理系统在数据库管理系统中,属性是数据表中的列,它描述了每一条数据记录的特定内容。

属性的定义和设计对于数据的组织和查询具有重要意义。

浅谈js中的attributes和Attribute的用法与区别

浅谈js中的attributes和Attribute的用法与区别

浅谈js中的attributes和Attribute的⽤法与区别⼀:Attribute的⼏种⽤法和含义(attributes和Attribute都是⽤来操作属性的)getAttribute:获取某⼀个属性的值;setAttribute:建⽴⼀个属性,并同时给属性捆绑⼀个值;createAttribute:仅建⽴⼀个属性;removeAttribute:删除⼀个属性;getAttributeNode:获取⼀个节点作为对象;setAttributeNode:建⽴⼀个节点;removeAttributeNode:删除⼀个节点;1.getAttribute:<body><div id = "t"><input type = "hidden" id = "sss" value = "aaa"></div></body><script>var d=document.getElementById("sss").getAttribute("value");console.log(d) //aaa;</script>get 取得的返回值是属性值。

2.setAtribute:<div id = "t"><input type = "hidden" id = "sss" value = "aaa"></div></body><script>var d = document.createAttribute("good");document.getElementById("sss").setAttributeNode(d);alert(document.getElementById("t").innerHTML) //弹出框<input type="hidden" id="sss" value="aaa" good="">; //多了⼀个属性为good;但是没有给其设置属性值;所以为空。

C#自定义特性

C#自定义特性

C#⾃定义特性特性是⼀种允许我们向程序集增加元数据的语⾔结构,它是⽤于保存程序结构信息的某种特殊类型的类。

根据惯例,特性名使⽤Pascal命名法并且以Attribute后缀结尾。

当为⽬标应⽤特性时,我们可以不使⽤后缀。

例如对于SerializableAttribute和MyAttributeAttribute这两个特性,我们在把他们应⽤到结构时可以使⽤Serializable和MyAttribute短名称。

所有特性类都派⽣⾃System.Attribute,⽤户⾃定义的特殊类叫做⾃定义特性。

声明⾃定义特性派⽣⾃System.Attribute起⼀个以后缀为Attribute结尾的名字为安全起见,建议声明⼀个sealed的特性类由于特性持有⽬标的信息,所以特性类的公共成员只能是:字段,属性,构造函数。

使⽤特性的构造函数和其他类⼀样,都有构造函数,每⼀个特性⾄少必须有⼀个公共构造函数,如果不声明构造函数,编译器会为我们产⽣⼀个隐式,公共且⽆参的构造函数,也可以被重载,声明构造函数时,必须使⽤类全名(即包括后缀)。

在应⽤时,才可以使⽤短名称(不包括后缀)。

[MyAttribute("Holds a value")] //使⽤了⼀个字符串的构造函数,它只是声明语句,只有特性的消费者访问特性时候才能调⽤构造函数,它不会决定什么时候构造特性类的对象。

public int MyField;构造函数中的位置参数和命名参数[MyAttribute("An excellent class",Review="Amy",ver="0.7.1")]第⼀个参数是位置参数,后两个是命名参数。

public sealed class MyAttributeAttribute:System.Attribute{public string Description;public string Ver;public string Reviewer;public MyAttributeAttribute(string desc){Description=desc;}}[MyAttribute("Excellent class",Reviewer="CJ266",Ver="0.7.1")] //虽然构造函数只有⼀个形参,但我们可以通过命名参数给构造函数3个实参,这与普通的类是不⼀样的。

c#属性类(特性)

c#属性类(特性)

c#属性类(特性)前⾔c# 属性类也称做特性。

这是⼀篇垫⽂,为后⾯的过滤器和其他特性类的东西做铺垫。

正⽂看⼀段代码:static void Main(string[] args){Attribitefunc1.printMesssage("卡特林");Console.ReadLine();}/// <summary>/// Attribitefunc1 is class that provite a print method/// </summary>public class Attribitefunc1{[Conditional("release")]public static void printMesssage(string msg){Console.WriteLine("输出数据:"+ msg);}}然后发现不会有任何输出;然后我加上#define release;结果:那么我们明⽩原来这个是否执⾏是根据是否预处理来判断的,这使得我们程序变得很⽅便。

再举⼀个例⼦:我们在开发⼀个项⽬中,如果我们废弃了代码,我们是不会去⽴即删除的,因为需要回顾历史。

static void Main(string[] args){Attribitefunc1.printMesssage("卡特林");Console.ReadLine();}/// <summary>/// Attribitefunc1 is class that provite a print method/// </summary>public class Attribitefunc1{[Obsolete("this is old",true)]public static void printMesssage(string msg){Console.WriteLine("输出数据:"+ msg);}}这时候显⽰的是:当然有时候我们是不会让他报错的,只需要警告。

C#自定义特性(Attribute)详解

C#自定义特性(Attribute)详解

C#⾃定义特性(Attribute)详解编写⾃定义特性[FieldName("Social")]public string SocialNumber{...}当C#编译器发现SocialNumber属性应⽤了⼀个FieldName特性时,⾸先会把字符串Attribute追加到FieldName这个名称后⾯,形成⼀个组合名称FieldNameAttribute,然后在其搜索路径的所有名称空间(即在using语句中提及的名称空间)中搜索FieldNameAttribute类。

但如果该特性的名称以字符串Attribute结尾,编译器就不会把这个字符串加到组合名称中。

因此上⾯的代码等价于:[FieldNameAttribute("Social")]public string SocialNumber{...}1.AttributeUsage特性⾃定义的特性类需要直接或间接派⽣⾃System.Attribute。

这个类还应包含控制⽤法的信息:*特性可以应⽤到哪些类型的程序元素上(类,结构,属性和⽅法等)*特性是否可以多次应⽤到同⼀个程序元素上*特性在应⽤到类或接⼝上时,是否由派⽣类和接⼝继承*这个特性有哪些必选和可选参数如果编译器找不到对应的特性类,或者找到⼀个这样的特性类,但使⽤特性的⽅式与特性类中的信息不匹配,编译器就会产⽣⼀个编译错误。

定义FieldNameAttribute特性[AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=false)]public class FieldNameAttribute:Attribute{private string name;public FieldNameAttribute(string name){ = name;}}特性类FieldNameAttribute本⾝⽤了⼀个特性System.AttributeUsage来标记。

特性的使用,校验long长度

特性的使用,校验long长度

特性的使⽤,校验long长度1 特性attribute定义:是⼀个类,编译时决定,不能使⽤变量2 声明和使⽤attribute,AttributeUsage3 运⾏中获取attribute:额外信息额外操作4 Remark封装、attribute验证特性的使⽤:1.定义T的扩展⽅法:Validatepublic static bool Validate<T>(this T t){Type type = t.GetType();foreach (var prop in type.GetProperties()){if (prop.IsDefined(typeof(AbstractValidateAttribute), true)){object oValue = prop.GetValue(t);foreach (AbstractValidateAttribute attribute in prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true)) {if (!attribute.Validate(oValue))return false;}}}return true;}2. 定义校验基类AbstractValidateAttribute和需要校验的long类型:LongAttributepublic abstract class AbstractValidateAttribute : Attribute{public abstract bool Validate(object oValue);}定义long校验类[AttributeUsage(AttributeTargets.Property)]public class LongAttribute : AbstractValidateAttribute{private long _Min = 0;private long _Max = 0;public LongAttribute(long min, long max){this._Min = min;this._Max = max;}public override bool Validate(object oValue){return oValue != null&& long.TryParse(oValue.ToString(), out long lValue)&& lValue >= this._Min&& lValue <= this._Max;}}4.model 属性的校验:public class Student{[Long(10000, 999999999999)]public long QQ { get; set; }}Student student = new Student()if (student.Validate()){Console.WriteLine("特性校验成功");}------------------------------第3⽅主动使⽤特性,特性才有作⽤,特性本⾝就⼀个类-----------------------------public static void ManagerStudent<T>(T student) where T : Student{Console.WriteLine($"{student.Id}_{}");student.Study();student.Answer("123");Type type = student.GetType();if (type.IsDefined(typeof(CustomAttribute), true)){//type.GetCustomAttribute()object[] oAttributeArray = type.GetCustomAttributes(typeof(CustomAttribute), true);foreach (CustomAttribute attribute in oAttributeArray){attribute.Show();//attribute.Description}foreach (var prop in type.GetProperties()){if (prop.IsDefined(typeof(CustomAttribute), true)){object[] oAttributeArrayProp = prop.GetCustomAttributes(typeof(CustomAttribute), true);foreach (CustomAttribute attribute in oAttributeArrayProp){attribute.Show();}}}foreach (var method in type.GetMethods()){if (method.IsDefined(typeof(CustomAttribute), true)){object[] oAttributeArrayMethod = method.GetCustomAttributes(typeof(CustomAttribute), true); foreach (CustomAttribute attribute in oAttributeArrayMethod){attribute.Show();}}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

AttributeUsage属性除了定制attributes之外,可以使用Attributes属性定义如何使用这些属性。

例如:[AttributeUsage( validon,AllowMultiple = allowmultiple,Inherited = inherited)]强烈推荐使用AttributeUsage属性将属性文档化,因此属性的用户能直接使用已命名的属性,而不用在源代码中查找公用的读/写字段和属性。

定义属性目标1public enum AttributeTargets2{3Assembly = 0x0001,4Module = 0x0002,5Class = 0x0004,6Struct = 0x0008,7Enum = 0x0010,8Constructor = 0x0020,9Method = 0x0040,10Property = 0x0080,11Field = 0x0100,12Event = 0x0200,13Interface = 0x0400,14Parameter = 0x0800,15Delegate = 0x1000,16All = Assembly │ Module │ Class │ Struct │ Enum │ Constructor │17Method │ Property │ Field │ Event │ Interface │ Parameter │18Delegate,1920ClassMembers = Class │ Struct │ Enum │ Constructor │ Method │21Property │ Field │ Event │ Delegate │ Interface,22}23当使用Attribute属性时,能指定AttributeTargets.all(属性目标),因此属性能被附加到在枚举Attribute Targets列出的任意类型上。

若未指定AttributeUsage属性,缺省值是AttributeTargets.All。

属性Attribut eTargets用来限制属性使用范围。

1[AttributeUsage(AttributeTargets.Class)]2public class RemoteObjectAttribute : Attribute3{4…5}67[AttributeUsage(AttributeTargets.Method)]8public class TransactionableAttribute : Attribute9{10111213}14可以使用或(|)操作符组合属性目标枚举中列出的项。

单一用途和多用途属性可以使用AttributeUsage定义属性的单一用途或多用途。

即确定在单个字段上使用单一属性的次数。

在缺省情况下,所有属性都是单用途的。

在AttributeUsage属性中,指定AllowMultiple 为true,则允许属性多次附加到指定的类型上。

例如:1[AttributeUsage(AttributeTargets.All, AllowMultiple=true)]2public class SomethingAttribute : Attribute3{4public SomethingAttribute(String str)5{6}7}89[Something("abc")]10[Something("def")]11class MyClass12{13}14指定继承属性规则在AttributeUsageAttribute属性的最后部分是继承标志,用于指定属性是否能被继承。

缺省值是false。

然而,若继承标志被设置为true,它的含义将依赖于AllowMultiple标志的值。

若继承标志被设置为true,并且AllowMultiple标志是flag,则改属性将忽略继承属性。

若继承标志和AllowMultiple标志都被设置为true,则改属性的成员将与派生属性的成员合并。

范例:1using System;2using System.Reflection;34namespace AttribInheritance5{6[AttributeUsage(7AttributeTargets.All,8AllowMultiple = true,9//AllowMultiple = false,10Inherited = true11)]12public class SomethingAttribute : Attribute 13{14private string name;15public string Name16{17get{ return name; }18set{ name = value; }19}2021public SomethingAttribute(string str)22{ = str;24}25}2627[Something("abc")]28class MyClass29{30}3132[Something("def")]33class Another : MyClass34{35}3637class Test38{39[STAThread]40static void Main(string[] args)41{42Type type =43Type.GetType("AttribInheritance.Another");44foreach(Attribute attr in type.GetCustomAttributes(true))45//type.GetCustomAttributes(false))46{47SomethingAttribute sa =48attr as SomethingAttribute;49if(null!= sa)50{51Console.WriteLine(52"Custom Attribute: {0}",);54}55}//foreach5657}//main58}//Test59}//namespace60若AllowMultiple设置为false,结果是:Custom Attribute: def若AllowMultiple设置为true,结果是:Custom Attribute: defCustom Attribute: abcC# AttributeUsage的使用浅析C# AttributeUsage的使用是如何的呢?首先让我们来了解一下什么是AttributeUsage类它是另外一个预定义特性类,AttributeUsage类的作用就是帮助我们控制定制特性的使用。

其实AttributeUsage类就是描述了一个定制特性如何被使用。

C# AttributeUsage的使用要明白:AttributeUsage有三个属性,我们可以把它放置在定制属性前面。

第一个属性是:◆ValidOn通过这个属性,我们能够定义定制特性应该在何种程序实体前放置。

一个属性可以被放置的所有程序实体在AttributeTargets enumerator中列出。

通过OR操作我们可以把若干个AttributeTargets 值组合起来。

◆AllowMultiple这个属性标记了我们的定制特性能否被重复放置在同一个程序实体前多次。

◆Inherited我们可以使用这个属性来控制定制特性的继承规则。

它标记了我们的特性能否被继承。

C# AttributeUsage的使用实例:下面让我们来做一些实际的东西。

我们将会在刚才的Help特性前放置AttributeUsage特性以期待在它的帮助下控制Help特性的使用。

1using System;2[AttributeUsage(AttributeTargets.Class), AllowMultiple = false,3Inherited = false ]4public class HelpAttribute : Attribute5{6public HelpAttribute(String Description_in)7{8this.description = Description_in;9}10protected String description;11public String Description12{13get14{15return this.description;16}17}18}先让我们来看一下AttributeTargets.Class。

它规定了Help特性只能被放在class的前面。

这也就意味着下面的代码将会产生错误:19[Help("this is a do-nothing class")]20public class AnyClass21{22[Help("this is a do-nothing method")] //error23public void AnyMethod()24{25}26}编译器报告错误如下:27AnyClass.cs: Attribute 'Help' is not valid on this declaration type.2829It is valid on 'class' declarations only.我们可以使用AttributeTargets.All来允许Help特性被放置在任何程序实体前。

可能的值是:30Assembly,31Module,32Class,33Struct,34Enum,35Constructor,36Method,37Property,38Field,39Event,40Interface,41Parameter,42Delegate,43All = Assembly | Module | Class |44Struct | Enum | Constructor |45Method | Property | Field | Event |46Interface | Parameter | Delegate,47ClassMembers = Class | Struct | Enum |48Constructor | Method | Property | Field |49Event | Delegate | Interface )下面考虑一下AllowMultiple = false。

相关文档
最新文档