// 已知 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());//方法調用
}
}