文链接:https://www.infoworld.com/article/3006630/how-to-work-with-attributes-in-c.html?nsdr=true
Attribute 在 C# 中是一个非常强大的特性,它能够给你的程序集添加元数据信息。
Attribute 实际上是一个对象,它可以与以下元素中的任何一个相关联: 程序集、类、方法、委托、枚举、事件、字段、接口、属性和结构,它会在这些对象上做信息声明,当程序运行之后,你可以通过反射来获取关联到这些对象上的 Attribute 信息,换句话说:你可以通过 Atrribute 向程序集注入一些额外信息,然后在运行时通过反射来获取,attribute 一般由 名字 + 一些可选参数
构成, attribute 名字对应着 atrribute 类。
你可以利用 attribute 去校验你的业务model的正确性, attribute 有两种:内置 + 自定义
, 前者是 .net framework 框架的组成部分,后者需要通过继承 System.Attribute
类来实现自定义。
现在来看看代码怎么写,Obsolete
特性用来标记一个方法是过时的,这个过时的意思是:你不应该再使用这个方法了,未来框架也会将其剔除,目前也存在其替代方案
。其实在第三方框架中有很多这样的例子,下面的代码片段展示了如何在方法顶部使用 Obsolete
特性。
[Obsolete("This method is obsolete...")]
public static void DoSomeWork()
{
}
如果你在程序中调用了这个方法,当你编译代码时,在 Visual Studio 输出窗口中会现在一些警告信息,如下图:
当然,如果你一定要忽视它也是可以的,现在,假如你希望你的开发同事不允许调用这个方法,那如何去限定呢?哈哈,可以使用 Obsolete 的第二个参数,这个参数是可选的,下面是 DoSomeWork()
方法的修改版本,请注意这是一个 Boolean 型参数。
[Obsolete("This method is obsolete...", true)]
public static void DoSomeWork()
{
}
当把 true 给了这个可选参数后,再次编译代码,你会发现代码根本编译不通过,是不是完美的解决了你的问题,是吧! 截图如下:
这一小节我们来看一下如何去实现自定义的 attribute,要想自定义实现,可以创建一个类并继承 System.Attribute
类即可,如下代码所示:
using System;
public class CustomAttribute : Attribute
{
}
要想限定 CustomAttribute 的使用,可以用 AttributeUsage 类去标记,这个类包含了如下属性: ValidOn
,AllowMultiple
,Inherited
等等,这些标记都可以限定 CustomAttribute 的使用。
下面的代码片段展示了 CustomAttribute 的修改版本,这个类使用构造函数去给内部的私有 string 赋值,代码仅仅用于演示目的。
[AttributeUsage(AttributeTargets.All)]
public class CustomAttribute : Attribute
{
private string text;
public CustomAttribute(string text)
{
this.Text=text;
}
public string Text { get=> text; set=> text=value; }
}
当然你也可以按需去指定这些 AttributeTargets,如下代码所示:
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple=true)]
public class CustomAttribute : Attribute
{
private string text;
public CustomAttribute(string text)
{
this.Text=text;
}
public string Text { get=> text; set=> text=value; }
}
接下来你可以用反射来获取应用到对象上的所有attributes,代码如下:
static void Main(string[] args)
{
MemberInfo memberInfo=typeof(CustomAttribute);
object[] attributes=memberInfo.GetCustomAttributes(true);
for (int i=0, j=attributes.Length; i < j; i++)
{
Console.WriteLine(attributes[i]);
}
}
接下来我准备将 CustomAttribute 类应用到 下面的 SomeClass 类上。
[CustomAttribute("Hello World...")]
public class SomeClass
{
}
可以着重看下 CustomAttribute 是如何安插在 SomeClass 上的,而且我还传递了一个 Hello World...
字符串给它,下面的代码展示了如何将 CustomAttribute 中的 Text 属性打印出来。
class Program
{
static void Main(string[] args)
{
MemberInfo memberInfo=typeof(SomeClass);
object[] attributes=memberInfo.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
CustomAttribute customAttribute=attribute as CustomAttribute;
if (customAttribute !=null)
Console.WriteLine("Text={0}", customAttribute.Text);
else
Console.WriteLine();
}
}
}
[CustomAttribute("Hello World...")]
public class SomeClass
{
}
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple=true)]
public class CustomAttribute : Attribute
{
private string text;
public CustomAttribute(string text)
{
this.Text=text;
}
public string Text { get=> text; set=> text=value; }
}
更多高质量干货:参见我的 GitHub: dotnetfly**
NU C的一大特色(却不被初学者所知)就是 attribute 机制。
attribute可以设置函数属性(Function Attribute)、变量属性(Variable Attribute) 和 类型属性(Type Attribute)。
attribute书写特征是: attribute前后都有两个下划线,并且后面会紧跟一对圆括弧,括弧里面是相应的attribute参数。
attribute语法格式为:
__attribute__ ((attribute-list))
其位置约束为: 放于声明的尾部“;”之前。
函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。
attribute机制也很容易同非GNU应用程序做到兼容之功效。
GNU CC需要使用 –Wall编译器来激活该功能,这是控制警告信息的一个很好的方式。
下面介绍几个常见的属性参数。
该attribute属性可以给被声明的函数加上类似printf或者scanf的特征,它可以使编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配。
该功能十分有用,尤其是处理一些很难发现的bug。
format的语法格式为:
format (archetype, string-index, first-to-check)
format属性告诉编译器,按照printf, scanf, strftime或strfmon的参数表格式规则对该函数的参数进行检查。
具体使用格式如下:
__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))
其中参数m与n的含义为:
m:第几个参数为格式化字符串(format string);
n:参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几,注意,有时函数参数里还有“隐身”的呢,后面会提到;
在使用上,attribute((format(printf,m,n)))是常用的,而另一种却很少见到。
下面举例说明,其中myprint为自己定义的一个带有可变参数的函数,其功能类似于printf:
//m=1;n=2
extern void myprint(const char *format,...)
__attribute__((format(printf,1,2)));
//m=2;n=3
extern void myprint(int l,const char *format,...)
__attribute__((format(printf,2,3)));
需要特别注意的是,如果myprint是一个函数的成员函数,那么m和n的值可有点“悬乎”了,例如:
//m=3;n=4
extern void myprint(int l,const char *format,...)
__attribute__((format(printf,3,4)));
其原因是,类成员函数的第一个参数实际上是一个 “隐身”的“this”指针。(有点C++基础的都知道点this指针,不知道你在这里还知道吗?)
这里给出测试用例:attribute.c,代码如下:
1:
2:extern void myprint(const char *format,...)
__attribute__((format(printf,1,2)));
3:
4:void test()
5:{
6: myprint("i=%d\n",6);
7: myprint("i=%s\n",6);
8: myprint("i=%s\n","abc");
9: myprint("%s,%d,%d\n",1,2);
10:}
运行 $gcc –Wall –c attribute.c attribute后,输出结果为:
attribute.c: In function `test':
attribute.c:7: warning: format argument is not a pointer (arg 2)
attribute.c:9: warning: format argument is not a pointer (arg 2)
attribute.c:9: warning: too few arguments for format
如果在attribute.c中的函数声明去掉attribute((format(printf,1,2))),再重新编译,
既运行$gcc –Wall –c attribute.c attribute后,则并不会输出任何警告信息。
注意,默认情况下,编译器是能识别类似printf的“标准”库函数。
该属性通知编译器函数从不返回值,当遇到类似函数需要返回值而却不可能运行到返回值处就已经退出来的情况,该属性可以避免出现错误信息。
C库函数中的abort()和exit()的声明格式就采用了这种格式,如下所示:
extern void exit(int) __attribute__((noreturn));
extern void abort(void) __attribute__((noreturn));
为了方便理解,大家可以参考如下的例子:
//name: noreturn.c ;测试__attribute__((noreturn))
extern void myexit();
int test(int n)
{
if ( n > 0 )
{
myexit();
/* 程序不可能到达这里*/
}
else
return 0;
}
编译显示的输出信息为:
$gcc –Wall –c noreturn.c
noreturn.c: In function `test':
noreturn.c:12: warning: control reaches end of non-void function
警告信息也很好理解,因为你定义了一个有返回值的函数test却有可能没有返回值,程序当然不知道怎么办了!
加上__attribute__((noreturn))则可以很好的处理类似这种问题。把
extern void myexit();修改为:
extern void myexit() __attribute__((noreturn));之后,编译不会再出现警告信息。
该属性只能用于带有数值类型参数的函数上。
当重复调用带有数值参数的函数时,由于返回值是相同的,所以此时编译器可以进行优化处理,除第一次需要运算外,其它只需要返回第一次的结果就可以了,进而可以提高效率。该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。
为了说明问题,下面举个非常“糟糕”的例子,该例子将重复调用一个带有相同参数值的函数,具体如下:
extern int square(int n) __attribute__((const));
...
for (i=0; i < 100; i++ )
{
total +=square (5) + i;
}
通过添加attribute((const))声明,编译器只调用了函数一次,以后只是直接得到了相同的一个返回值。
事实上,const参数不能用在带有指针类型参数的函数中,因为该属性不但影响函数的参数值,同样也影响到了参数指向的数据,它可能会对代码本身产生严重甚至是不可恢复的严重后果。
并且,带有该属性的函数不能有任何副作用或者是静态的状态,所以,类似getchar()或time()的函数是不适合使用该属性的。
可以在同一个函数声明里使用多个attribute,并且实际应用中这种情况是十分常见的。
使用方式上,你可以选择两个单独的attribute,或者把它们写在一起,可以参考下面的例子:
/* 把类似printf的消息传递给stderr 并退出 */
extern void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf, 1, 2)));
或者写成
extern void die(const char *format, ...) __attribute__((noreturn, format(printf, 1, 2)));
如果带有该属性的自定义函数追加到库的头文件里,那么所以调用该函数的程序都要做相应的检查。
庆幸的是,attribute设计的非常巧妙,很容易作到和其它编译器保持兼容,也就是说,如果工作在其它的非GNU编译器上,可以很容易的忽略该属性。即使attribute使用了多个参数,也可以很容易的使用一对圆括弧进行处理,例如:
/* 如果使用的是非GNU C, 那么就忽略__attribute__ */
#ifndef __GNUC__#
define __attribute__(x) /*NOTHING*/
#endif
需要说明的是,attribute适用于函数的声明而不是函数的定义。
所以,当需要使用该属性的函数时,必须在同一个文件里进行声明,
例如:
/* 函数声明 */
void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf,1,2)));
void die(const char *format, ...)
{
/* 函数定义 */
}
更多的属性含义参考:http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html
关键字attribute也可以对变量(variable)或结构体成员(structure field)进行属性设置。
这里给出几个常用的参数的解释,更多的参数可参考本文给出的连接。
在使用attribute参数时,你也可以在参数的前后都加上“”(两个下划线),例如,使用__aligned而不是aligned,
这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。
该属性规定变量或结构体成员的最小的对齐格式,以字节为单位。例如:
int x __attribute__((aligned (16)))=0;
编译器将以16字节(注意是字节byte不是位bit)对齐的方式分配一个变量。
也可以对结构体成员变量设置该属性,例如,创建一个双字对齐的int对,可以这么写:
struct foo { int x[2] __attribute__((aligned (8))); };
如上所述,你可以手动指定对齐的格式,同样,你也可以使用默认的对齐方式。如果aligned后面不紧跟一个指定的数字值,那么编译器将依据你的目标机器情况使用最大最有益的对齐方式。例如:
short array[3] __attribute__((aligned));
选择针对目标机器最大的对齐方式,可以提高拷贝操作的效率。
aligned属性使被设置的对象占用更多的空间,相反的,使用packed可以减小对象占用的空间。
需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,那么你此时定义32字节对齐也是无济于事的。
使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。
下面的例子中,x成员变量使用了该属性,则其值将紧放置在a的后面:
struct test
{
char a;
int x[2] attribute ((packed));
};
其它可选的属性值还可以是:cleanup,common,nocommon,deprecated,mode,section,shared,tls_model,transparent_union,unused,vector_size,weak,dllimport,dlexport等,
详细信息可参考:http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes
关键字attribute也可以对结构体(struct)或共用体(union)进行属性设置。
大致有六个参数值可以被设定,即:
aligned, packed, transparent_union, unused, deprecated 和 may_alias。
在使用attribute参数时,你也可以在参数的前后都加上“”(两个下划线),例如,使用__aligned而不是aligned,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。
该属性设定一个指定大小的对齐格式(以字节为单位),例如:
struct S { short f[3]; } __attribute__ ((aligned (8)));
typedef int more_aligned_int __attribute__ ((aligned (8)));
该声明将强制编译器确保(尽它所能)变量类型为struct S 或者more-aligned-int的变量在分配空间时采用8字节对齐方式。
如上所述,你可以手动指定对齐的格式,同样,你也可以使用默认的对齐方式。
如果aligned后面不紧跟一个指定的数字值,那么编译器将依据你的目标机器情况使用最大最有益的对齐方式。例如:
struct S { short f[3]; } __attribute__ ((aligned));
这里,如果sizeof(short)的大小为2(byte),那么,S的大小就为6。取一个2的次方值,使得该值大于等于6,则该值为8,所以编译器将设置S类型的对齐方式为8字节。
aligned属性使被设置的对象占用更多的空间,相反的,使用packed可以减小对象占用的空间。
需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,那么你此时定义32字节对齐也是无济于事的。
使用该属性对struct或者union类型进行定义,设定其类型的每一个变量的内存约束。
当用在enum类型定义时,暗示了应该使用最小完整的类型(it indicates that the smallest integral type should be used)。
下面的例子中,my-packed-struct类型的变量数组中的值将会紧紧的靠在一起,但内部的成员变量s不会被“pack”,如果希望内部的成员变量也被packed的话,my-unpacked-struct也需要使用packed进行相应的约束。
struct my_unpacked_struct
{
char c;
int i;
};
struct my_packed_struct
{
char c;
int i;
struct my_unpacked_struct s;
}__attribute__ ((__packed__));
其它属性的含义见: http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html#Type-Attributes
下面的例子中使用attribute属性定义了一些结构体及其变量,并给出了输出结果和对结果的分析。
程序代码为:
struct p
{
int a;
char b;
char c;
}__attribute__((aligned(4))) pp;
struct q
{
int a;
char b;
struct n qn;
char c;
}__attribute__((aligned(8))) qq;
int main()
{
printf("sizeof(int)=%d,sizeof(short)=%d.sizeof(char)=%d\n",sizeof(int),sizeof(short),sizeof(char));
printf("pp=%d,qq=%d \n", sizeof(pp),sizeof(qq));
return 0;
}
输出结果:
sizeof(int)=4,sizeof(short)=2.sizeof(char)=1
pp=8,qq=24
分析:
sizeof(pp):
sizeof(a)+ sizeof(b)+ sizeof(c)=4+1+1=6<23=8=sizeof(pp)
sizeof(qq):
sizeof(a)+ sizeof(b)=4+1=5
sizeof(qn)=8; 即qn是采用8字节对齐的,所以要在a,b后面添3个空余字节,然后才能存储qn,
4+1+(3)+8+1=17
因为qq采用的对齐是8字节对齐,所以qq的大小必定是8的整数倍,即qq的大小是一个比17大又是8的倍数的一个最小值,由此得到
17<24+8=24=sizeof(qq)
更详细的介绍见:http://gcc.gnu.org/
Reference:
1.有关attribute的相对简单的介绍:http://www.unixwiz.net/techtips/gnu-c-attributes.html
2.attribute详细介绍:http://gcc.gnu.org/
DOM节点是一个JS对象,它符合前面描述的对象的特性——可扩展属性,因为DOM节点本质上也是一个JS。因此,如以下代码所示,“p”可以具有“style”属性和“className”“nodeName”“nodeType”属性。注意**这些是JS类别的属性,符合JS语法标准的**。
var pList=document.querySelectorAll('p')
var p=pList[0]
console.log(p.style.width) // 获取样式
p.style.width='100px' // 修改样式
console.log(p.className) // 获取 class
p.className='p1' // 修改 class
// 获取 nodeName 和 nodeType
console.log(p.nodeName)
console.log(p.nodeType)
property 的获取和修改,是直接改变 JS 对象,而 attribute 是直接改变 HTML 的属性,两种有很大的区别。attribute 就是对 HTML 属性的 get 和 set,和 DOM 节点的 JS 范畴的 property 没有关系。
var pList=document.querySelectorAll('p')
var p=pList[0]
p.getAttribute('data-name')
p.setAttribute('data-name', 'juejin')
p.getAttribute('style')
p.setAttribute('style', 'font-size:30px;')
而且,get 和 set attribute 时,还会触发 DOM 的查询或者重绘、重排,频繁操作会影响页面性能。
*请认真填写需求信息,我们会在24小时内与您取得联系。