反射能做的事:
- 枚举类型的成员
- 实例化新对象
- 执行对象的成员
- 查找类型的信息
- 查找程序集的信息
- 检查应用于某种类型的自定义特性
- 创建和编译新程序集
特性:
[AttributeUsage(AttributeTargets.Property,AllowMultiple =false,Inherited =false)]
public class FieldNameAttribute : Attribute
{
private string name;
public string Comment { get; set; }
public FieldNameAttribute(string name)
{
this.name = name;
}
}
AttributeUsage 来标记Attribute,标识自定义特性可以应用到哪些类型的程序元素上。第一个参数必选AttributeTargets
System.Type类
获取指向任何类型 的Type引用有3种方式:
- 使用typeof运算符:
Type t=typeof(double);
- 使用GetType()方法,所有类都会从System.Object继承这个方法
double d = 10;
Type t = d.GetType();
- 调用Type类的静态方法GetType()
Type tt = Type.GetType("System.Double");
Type是许多反射功能的入口。
Type的属性:
Name 数据类型名
FullName 数据类型 的完全限定名 包括名称空间名
NameSpace 命名空间名
Assembly类
把相应的程序集加载到正在运行的进程中。
Assembly.Load() 参数是程序集名称
Assembly.LoadFrom() 参数是程序集的完整路径名
从程序集获取自定义特性:
var ass = Assembly.Load("");
Attribute[] definedAttributes = Attribute.GetCustomAttributes(ass);
动态实例化类型
NET46
var ass = Assembly.Load("");
var instance = ass.CreateInstance("typename");
var ass = Assembly.Load("");
Type t = ass.GetType("");
var instance = Activator.CreateInstance(t);
调用方法
instance.GetType().InvokeMember("add", BindingFlags.InvokeMethod,
null, instance, new object[] { 1, 2 });
instance.GetType().GetMethod("add").Invoke(instance, new object[] { 1, 2 });
dynamic类型有两个限制:
- 动态对象不支持扩展方法
- lambda表达式也不能用作动态方法调用的参数
ExpandoObject创建动态类型
static void DoExpando()
{
dynamic expObj = new ExpandoObject();
expObj.FirstName = "CC";
expObj.LastName = "DD";
Console.WriteLine($"{expObj.FirstName} {expObj.LastName}");
Func<DateTime, string> GetTomorrow = t => t.AddDays(1).ToShortDateString();
expObj.GetTomorrowDate = GetTomorrow;
expObj.Friends = new List<Person>();
expObj.Friends.Add(new Person() { Name = "a" });
expObj.Friends.Add(new Person() { Name = "b" });
foreach (Person p in expObj.Friends)
{
Console.WriteLine(p.Name);
}
}