zoukankan      html  css  js  c++  java
  • 泛型方法 —— 动态设置方法所需的特定类型

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

      

  • 相关阅读:
    机器学习数学符号解释
    JVM Guide
    Mysql优化
    JAVA必会算法--冒泡排序
    HashMap-JDK源码阅读
    vue 下载文件
    CommonMethod
    log4net 写日志
    WebAPI 封装返回值
    二, .NET Core 微服务学习 ——集中式代理-Nginx
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/12895200.html
Copyright © 2011-2022 走看看