目录
一、 特性的定义及使用
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]
一般用于方法,指示编译器在生成堆栈跟踪信息时隐藏标记了该属性的方法,以提高代码的安全性和可读性。
[__DynamicallyInvokable]
用于 .NET Framework 中的特性之一,这个特性通常用于标记在动态语言运行时中可以进行调用的方法或属性,以便与动态语言交互。
当一个方法或属性被标记为 [__DynamicallyInvokable],它表明这个成员在动态语言的环境中是可调用的。换句话说,这个特性可以让动态语言运行时(比如 DLR,动态语言运行时)知道哪些成员是可以被调用的。这对于与动态语言交互的.NET 应用程序来说非常重要。
在大多数情况下,开发人员不需要直接使用 [__DynamicallyInvokable] 特性,因为它通常由框架或库内部使用。这个特性是为了支持.NET Framework 4.0引入的动态语言运行时而设计的,而在后续版本的.NET中可能已经有了更好的替代方案。