zl程序教程

您现在的位置是:首页 >  后端

当前栏目

asp.net 高级应用 特性Attribute ( 声明,原理,扩展,AOP)

2023-09-11 14:13:57 时间

特性attribute: 修饰作用


attribute声明,标识,生效,原理,扩展,aop思想的体现;
attribute声明:[]放在方法上,或类上,属性上,起修饰作用
1.常见的特性(你知道特性吗?用过吗?你知道的特性举例说明一下):
[Obsolete(“请使用xxx代替”,ture)]://影响编译器
[Serialize]//序列化
[httpPost]
[httpGet]//mvc webapi
[webMethod]//webservice 只有加了这个标记,才可以做为webservice接口使用
[ServiceContract]//wcf
[DependencyInjection]//IOC
[Required table key]//ORM

2.特性有什么用?
只有加了这个标记,才可以做为xxx接口使用,否则外部不能识别。

3.为什么加了此特性,会被发现为服务?
a>特性attribute:就是一个类,直接,间接继承自Attribute,一般以attribute结尾,标记时可以省略
b>特性有什么用:声明--标记
给属性添加特性后,在属性内部产生了一个.custom的元素;
ILSPY :反编译工具
IL:编译的中间语言,看IL能更深刻理解C#代码
c>特性是怎么生效的?
c#反射reflection 可以获取并使用metadata,在程序运行额过程中通过反射,可以检测到特性,获取特性实例,使用特性的实例;

d>ServiceContract为什么可以变成服务呢?
ServiceContract标记到接口,检测ServiceContract特性,有才展示,没有的不展示;

特性attribute本身没有价值,必须在程序运行的过程中,用反射主动发现并使用才有价值;

4>AOP 面向切面编程;
在不破坏封装的前提下,去增加额外的功能;

调用别人的接口返回的数据MODEL想转换为自己的MODEL(数据库MODEL,页面viewmodel)
一个类转换为另一个类model

1.利用反射 转换: 一个类转换为另一个类model
StudentDto dto=Trans<Student,Studentdto>(student);
PeopleDto dto=Trans<People,PeopleDto>(people);

private static Tout Trans<Tin,Tout>(Tin,tin)
{
Type typeOut=typeof(Tout);
Type typeIn=typeof(Tin);
Tout tout=(Tout)Activator.CreateInstance(typyOut);
//属性
foreach(var pro in typeOut.GetProperties()){
PropertyInfo propIn=typeIn.GetProperties(prop.Name);
object ovalue=propin.GetValue(tin);
prop.SetValue(tout,ovalue);
}
//字段
foreach(var field in typeOut.GetFields()){
FieldInfo fieldIn=typeIn.GetField(field.Name);
object ovalue=fieldIn.GetValue(tin);
fieldIn.SetValue(tout,ovalue);
}

return tout;
}


2.利用序列化json 转换,一个类转换为另一个类model
string sstudent=JsonConvert.SerializeObject(student);
StudentDto studentDto=JsonConvert.DeserializeObject<StudentDto>(sstudent);


3. automapper 类型转换工具,为ORM工具而生;
Mapper.Initialize(x=>x.createMap<Student,StudentDto>());
StudentDto dto=Mapper.Map<Student,StudentDto>(student);


4.动态生成硬编码,表达式目录树:expression
性能好,无法通用;通用性能不好。
new List<int>().AsQueryable().where(i=>i>5);

Func<Student,StudentDto> func=s=>new StudentDto()
{
Id=s.Id,
Name=s.Name,
Age=s.Age
};
//动态拼装目录树