泛型方法 —— 动态设置方法所需的特定类型
// 已知 Type type // 已知 string file var method = this.GetType().GetMethod(nameof(ImportDatabaseFromCsv), BindingFlags.Instance | BindingFlags.Public); //获取泛型方法 var destMethod = method.MakeGenericMethod(type);//设置泛型对应的特定类型 destMethod.Invoke(this, new object[] { file });//调用泛型方法 & 传参
//泛型方法 public void ImportDatabaseFromCsv<T>(string file) where T : class { //…… }
//moq中对泛型的应用 public class CustomerDefaultValueProvider<T> : DefaultValueProvider where T : class { T _instance; public CustomerDefaultValueProvider(T instance) { _instance = instance; } protected override object GetDefaultValue(Type type, Mock mock) { return type.IsValueType ? Activator.CreateInstance(type) : null; } protected override object GetDefaultReturnValue(MethodInfo method, Mock mock) { if (_instance == null) { return base.GetDefaultReturnValue(method, mock); } var targetMethods = mock.Invocations.Where(r => r.Method.Name == method.Name).LastOrDefault();//根据方法名,筛选可调用的方法 List<object> para = new List<object>(); para.AddRange(targetMethods.Arguments);//获取参数 return method.Invoke(_instance, para.ToArray());//方法调用 } }