using AttributeDemo.AttributeFile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AttributeDemo
{
class Program
{
/*
特性本身没有什么用?除非进行反射获取到特性,利用特性做点啥才有意义
*/
static void Main(string[] args)
{
//什么是特性 ?官方定义和直观例子,简单理解就是,声明属性,类的特征,标记谁写的,初始化一些信息声明,条件等等
//粗浅地理解为外在修饰信息,区别自身的一些字段,属性等信息,
//https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/attributes/
//直观地一些感受,标记某个类过期,
//new TestClass();//提示该类已经过时
//Obsolete是系统提供的一个特性
/*
* 延伸,面试题中常见情形,一个开放话题,由答案再次提问,
* 你知道特性吗?它有什么用?
* 比如webserivce标记HttpPost提供post调用,
* 你了解websive么?
*/
MyClass my= new MyClass();
//通过IL查看得知,属性标记特性后,在MyClass的属性,内部
//新增一个类,自动生成一个元素,但是通过属性,由无法调用
//my.testInt;
//不管是对类进行修饰,还是对属性进行修饰,都会产生内部一个对应对象
//他的调用,实际上通过反射进行调用
Type myclass = my.GetType();
//判断自定义属性是否存在
if (myclass.IsDefined(typeof(MyAttribute),true))
{
//搜索指定的特性,返回的特性对象,而非特性的Type
//Type myattribute =(Type)myclass.GetCustomAttributes(typeof(MyAttribute), true).First();
MyAttribute myattribute =(MyAttribute)myclass.GetCustomAttributes(typeof(MyAttribute), true).First();
myattribute.Show();
//扩展复习一下,通过type原型得到实例化对象,三种方式:new CreateInstance Invoke
//Activitor.CreateInstance ,以及获得构造函数,进行Invoke方法
}
//那么系统内置,如何实现标记特性,便对外提供服务呢?比如wcf中的ServieConstract标记,
//系统检测标记,一旦检测到即提供对外,否则不对外即可
//再次扩展一下,特性和AOP切面编程思想不谋而合,在不破坏封装的前提下,去增加额外的操作
}
}
/*特性一定要声明:
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)],
* 即这个特性可被多次修饰,否则提示重复修饰,
* 另外特性本身就是一个类,这里[MyAttribute]相当于new MyAttribute()
* 此外关于属性可以用Desc=进行初始化,相当于new MyAttribute(){初始化}
*/
[MyAttribute]
[MyAttribute(12)]
[MyAttribute(true, "类修饰", Desc="各类进行描述特性",name="我是姓名")]
public class MyClass
{
[MyAttribute]
[MyAttribute(12234)]
[MyAttribute(true, "属性修饰", Desc = "各属性进行描述特性", name = "我是姓名")]
public int testInt;
public void Show() {
Console.WriteLine("测试特性调用");
}
}
//如何告诉别人,其他开发者这个类,已经失效呢?
[Obsolete("类已经过期")]
[Serializable]
public class TestClass{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AttributeDemo.AttributeFile
{
//有一些特性,用来修饰特性类,比如
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
class MyAttribute:Attribute
{
public MyAttribute() {
}
public MyAttribute(int x)
{
}
public MyAttribute(string name)
{
}
public MyAttribute(bool b,string str)
{
}
public string Desc;
public string name;
public void Show() {
Console.WriteLine("测试特性调用");
}
public Action action1;
public event Action event1;
}
}