.Net单元测试工具Nunit就是使用的反射机制,在写测试用例的时候规定包含测试方法的类附加上"TestFixture"属性,测试方法附加"Test"属性。
NUnit首先从指定的Assembly中找到标记有"TestFixture"的Type.然后再遍历每一个Type找出标记有"Test"的方法MemberInfo. 调用方法只需使用 MemberInfo 实例的Invoke方法。
反射的一些常用功能
1. 获取实例的类型。例如
int i = 16;
Type type = i.GetType();
Console.WriteLine(type);
输出为 "System.Int32".
2.获取程序集的完整的名称
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Console.WriteLine(assembly.FullName);
}
3.访问标记在类上的属性
Teacher teacher = new Teacher();
Type type = teacher.GetType();
Author author = Attribute.GetCustomAttribute(type, typeof(Author)) as Author;
if (author != null)
{
Console.WriteLine(author.BookName);
}
4. 访问标记在类中的方法上的属性以及调用方法
Teacher teacher = new Teacher();
Type type = teacher.GetType();
MethodInfo[] methodInfoArr = type.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
Console.WriteLine(methodInfoArr.Length);
foreach (MethodInfo methodInfo in methodInfoArr)
{
Console.WriteLine(methodInfo.Name);
Usage Usage = Attribute.GetCustomAttribute(methodInfo, typeof(Usage)) as Usage;
if (Usage != null)
{
methodInfo.Invoke(Activator.CreateInstance(type), null);
Console.WriteLine(Usage.Description);
}
}
下面是定义的属性类和使用属性类的Teacher类
[Author("God is a girl")]
public class Teacher
{
public string name;
public string Name
{
get { return name; }
set { name = value; }
}
public Teacher()
{
}
[Usage("Invoke by a instance")]
public void CallStudent()
{
Console.WriteLine("Calling student.....");
}
public static void CallSpeficStudent()
{
Console.WriteLine("Calling specific student.....");
}
}
public class Author : Attribute
{
private string bookName;
public string BookName
{
get { return bookName; }
set { bookName = value; }
}
public Author(string bookName)
{
this.bookName = bookName;
}
}
public class Usage : Attribute
{
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
public Usage(string description)
{
this.description = description;
}
}
.Net单元测试工具Nunit就是使用的反射机制,字写测试用例的时候规定包含测试方法的类附加上"TestFixture"属性,测试方法附加"Test"属性。
NUnit首先从指定的Assembly中找到标记有"TestFixture"的Type.然后再遍历每一个Type找出标记有"Test"的方法MemberInfo. 调用方法只需使用 MemberInfo 实例的Invoke方法。