• c# 技巧之 泛型方法


    泛型 指的是编译时不需要指定具体的参数类型,可以在运行时动态地赋予某一种数据类型的机制。  相信很多人对泛型类并不陌生,像Dictionary,List等结构都属于泛型类。有趣的是,一个函数/方法也可以泛化。

    假如我们需要些一个函数,这个函数负责某一种逻辑操作(例如排序、求和、个数统计等),而不关心具体要操作的数据类型是什么,那么为了使这个函数变得更通用,就可以写成泛型方法。

    举一个我遇到的简单例子:

    项目中经常要写读文件,生成key-value 结构的字典。 每次都写StreamReader 和 Dicitonary 的句子会让人感觉码农真是一份无聊的职业。于是写了一个通用的加载key-value 字典的泛型方法:

       class Common
        {    
            internal static Dictionary<T1, T2> LoadDict<T1, T2>(string file, char sep, bool hasHeader = false, int keyidx=0, int valueidx=1)
            {
                Dictionary<T1, T2> res = new Dictionary<T1, T2>();
                using (StreamReader rd = new StreamReader(file))
                {
                    string content = "";
                    if (hasHeader)
                        rd.ReadLine();
    
                    while ((content = rd.ReadLine()) != null)
                    {
                        string[] words = content.Split(sep);
                        T1 key = (T1) Convert.ChangeType(words[keyidx], typeof(T1));
                        T2 value = (T2)Convert.ChangeType(words[valueidx], typeof(T2));
    
                        if (!res.ContainsKey(key))
                            res.Add(key, value);
                    }
                }
    
                return res;
            }
        }

    这样只要调用Common.LoadDict<string,int>( filename, ...) 就可以了。这个函数就像是一个模板,在运行时再确定要使用什么样的数据类型。 

    注意其中关于类型转换的代码:

    T1 key = (T1) Convert.ChangeType(words[keyidx], typeof(T1));

    如果类型操作还有更细致的要求,那么可以这样:

    if (typeof(T) == typeof(int))    
    { ... }
    else if (typeof(T) == typeof(double))
    { ... }
    else 
     ...
  • 相关阅读:
    申论1
    why factory pattern and when to use factory pattern
    jvm的字符串池
    is assembler instruction and machine instuction atomic
    jvm本身的多线程机制
    final
    java类的加载
    path和classpath的用途
    jar -cmf file1 file2 file3命令
    MANIFEST.MF中的MF是什么意思
  • 原文地址:https://www.cnblogs.com/sylvanas2012/p/5347760.html
Copyright © 2020-2023  润新知