核心的类
- Activator
- Attribute
- Assembly
- Type
- ConstructorInfo
- MethodBase
- MemberInfo
- FieldInfo
- PropertyInfo
创建实例
// 无参构造函数
object obj = Activator.CreateInstance(targetType);
// 一个int类型参数的构造函数
object obj = Activator.CreateInstance(targetType, new object[] { 520 });
// 一个字符串类型参数的构造函数
object obj = Activator.CreateInstance(targetType,new object[] { "str"});
// 一个字符串类型和一个int类型参数的构造函数
object obj = Activator.CreateInstance(targetType, new object[] { "str", 520 });
// 调用私有构造函数
object obj = Activator.CreateInstance(targetType, true);
获取Type
var type = typeof(obj);
var type = obj.GetType();
var type = Type.GetType("System.Double");
var type = assembly.GetType("DB.MySql.MySqlHlper");
判断是否为异步方法
public static bool IsAsyncMethod(MethodInfo method)
{
if(method.ReturnType == typeof(Task)) return true;
return method.ReturnType.IsGenericType
&& method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>);
}