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

      

  • 相关阅读:
    修改MySQL表varchar字段的小实验
    MySQL5.6同步指定数据库
    Redis安装
    MongoDB安装
    RMAN备份注意事项
    Oracle Data Guard Protection Modes
    Linux Shell 文本处理工具
    ORACLE 收缩表空间的数据文件
    crfclust.bdb导致磁盘满
    undo管理
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/12895200.html
Copyright © 2011-2022 走看看