c#特性
1. 概括
c#中的特性是一种用于向代码元素添加元数据的机制。它们允许程序员在代码中添加额外的信息,以影响程序的行为、编译过程或提供其他元数据。特性在编写现代c#代码时变得越来越常见,因为它们提供了一种优雅的方法来实现元数据驱动的开发。
特性分为:框架自带特性(如:[required]、[authorize]、[route]、[httppost]等)和自定义特性,都继承system.attribute
2. 语法
定义特性类
以下是一个简单的特性类定义示例:
using system;
[attributeusage(attributetargets.class | attributetargets.method, allowmultiple = true)]
public class mycustomattribute : attribute
{
public string description { get; }
public mycustomattribute(string description)
{
description = description;
}
}
应用特性
将特性应用到代码元素上,可以使用以下语法:
[mycustom("类使用自定义特性")]
public class myclass
{
[mycustom("方法使用自定义特性")]
public void mymethod()
{
}
}
获取特性
要获取 mycustom 特性,您可以使用反射来检查某个类型或成员上是否应用了该特性,并且访问该特性的属性。下面是如何获取 mycustom 特性的示例代码:
// 获取 myclass 类上的 mycustom 特性
var classattributes = typeof(myclass).getcustomattributes(typeof(mycustomattribute), false);
foreach (mycustomattribute attribute in classattributes)
{
console.writeline($"myclass类使用的mycustom特性: {attribute.description}");
}
// 获取 myclass 类中 mymethod 方法上的 mycustom 特性
var methodinfo = typeof(myclass).getmethod("mymethod");
var methodattributes = methodinfo.getcustomattributes(typeof(mycustomattribute), false);
foreach (mycustomattribute attribute in methodattributes)
{
console.writeline($"mymethod方法使用的mycustom特性: {attribute.description}");
}
3. 应用场景
数据验证
在模型类上应用特性,以进行数据验证。例如,使用dataannotations中的特性来验证模型:
public class user
{
[required]
[stringlength(50)]
public string name { get; set; }
[range(18, 99)]
public int age { get; set; }
}
序列化和反序列化
控制对象的序列化和反序列化过程。例如,使用json.net中的特性来指定json属性的名称和行为:
public class product
{
[jsonproperty("product_name")]
public string name { get; set; }
[jsonignore]
public decimal price { get; set; }
}
描述性元数据
为枚举值或其他代码元素添加描述信息。例如,使用descriptionattribute为枚举值添加描述信息:
public enum status
{
[description("the task is pending")]
pending,
[description("the task is completed")]
completed
}
依赖注入
在依赖注入容器中标记服务以进行注入。例如,在asp.net core中,使用[inject]特性标记需要注入的服务:
[inject]
public class myservice
{
// this property will be injected by the di container
}
单元测试
在单元测试框架中使用特性标记测试方法。例如,在nunit中使用[test]特性标记测试方法:
[test]
public void testmethod()
{
// test code here
}
权限控制
使用特性进行权限控制。例如,在asp.net core中使用[authorize]特性标记需要授权的控制器或操作方法:
[authorize(roles = "admin")]
public class admincontroller : controller
{
// only accessible to users in the admin role
}
aop(面向切面编程)
通过特性实现aop,如日志记录、事务管理等。例如,在asp.net core中使用actionfilterattribute来实现日志记录:
public class logactionfilter : actionfilterattribute
{
public override void onactionexecuting(actionexecutingcontext context)
{
// log action execution start
base.onactionexecuting(context);
}
public override void onactionexecuted(actionexecutedcontext context)
{
// log action execution end
base.onactionexecuted(context);
}
}
总结
c#中的特性为程序员提供了一种强大的元数据驱动机制,可以应用于多种场景。通过在代码中定义和使用特性,可以增强代码的可读性、可维护性,并提供灵活的方式来控制程序的行为和属性。
发表评论