MSIPO技术圈 首页 IT技术 查看内容

C#-特性Attribute的定义、使用及常用特性(不定时更新)

2024-04-04

目录

一、 特性的定义及使用

1.自定义特性

2.使用特性

3.查找特性名

4.获取相应对象的特性名

二、常用部分特性


一、 特性的定义及使用

1.自定义特性

全继承自Attribute基类(使用前要给自定义特性赋予相关特性) 

[AttributeUsage(AtrributeTargets.Class|AttributeTargets.Method,AllowMultiple=true,Inherited=true)

//AttributeTargets.Class:允许放类上

//AllowMultiple:是否允许多个使用(同一个特性)

//Inherited:是否允许继承

class MyAttribute:Attribute

{

        public MyAtrribute(){}

        public MyAttribute(String str){}

}

2.使用特性

一般放在类、属性、方法。。上方(使用时Attribute可省略)

[My]

[My("name")]

3.查找特性名

自己定义一个类方法用于查找。

public class customtableattribute
    {
        static public string GetTableAttribute<T>(T mode) where T:class
        { 
            Type type = typeof(T);//获取传入数据类型
            if (type.IsDefined(typeof(TableAttribute), true))//判断相应特性被使用
            {
                var attribute = type.GetCustomAttributes(typeof(TableAttribute), true);
                //获取TableAttribute特性,true代表允许继承特性的派生类
                return ((TableAttribute)attribute[0]).TableName;//返回特性名
            }
            else 
            {
                return type.Name;
            }
        
        }
    }

4.获取相应对象的特性名

string str= customtableattribute.GetTableAttribute(student);

二、常用部分特性

 [Key]//说明这个属性是主键
 virtual public int Id { get; set; }
 [StringLength(maximumLength:50,MinimumLength =2)]//字符串长度
 public string Name { get; set; }
 [EmailAddress]//识别邮箱格式
 public string Email { get; set; }
 [Required]//属性不能为空
 public string Description { get; set; }
 [Display(Name="电话号码")]//显示字段别名
 public string PhoneNumber { get; set; }
[StructLayout(LayoutKind.Auto)]

一般用于结构体,告诉运行时自动选择最合适的结构体布局方式,以在不同平台上获得最佳性能和互操作性,并使代码更具灵活性。

[MethodImpl(MethodImplOptions.AggressiveInlining)]

一般用于方法,指示编译器在调用方法时进行积极的内联优化(调用方法的地方替换为目标方法的代码),以提高程序的性能。

[StackTraceHidden]

一般用于方法,指示编译器在生成堆栈跟踪信息时隐藏标记了该属性的方法,以提高代码的安全性和可读性。

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部