C# 泛型特化

Wesley13
• 阅读 914

C# 泛型不是 C++ 的模板类,并不支持特化和偏特化,但是使用一些技巧可以在一定程度上达到相同的目的。

原文是 po 在 stackoverflow 上的一个回答:A: Generic indexer overload specialization

一、泛型方法的特化

使用一个非泛型 helper 类和一个内嵌的泛型类可以实现对泛型方法的特化。

    internal static class IndexerImpl //non-generic static helper class
    {
        private static T IndexerDefaultImpl<T>(int i) => default(T); //default implementation

        private static T IndexerImpl2<T>(int i) => default(T); //another implementation for short/int/long

        private static string IndexerForString(int i) => (i * i).ToString(); //specialization for T=string
        private static DateTime IndexerForDateTime(int i) => new DateTime(i * i * i); //specialization for T=DateTime

        static IndexerImpl() //install the specializations
        {
            Specializer<string>.Fun = IndexerForString;
            Specializer<DateTime>.Fun = IndexerForDateTime;

            Specializer<short>.Fun = IndexerImpl2<short>;
            Specializer<int>.Fun = IndexerImpl2<int>;
            Specializer<long>.Fun = IndexerImpl2<long>;
        }

        internal static class Specializer<T> //specialization dispatcher
        {
            internal static Func<int, T> Fun;
            internal static T Call(int i)
                => null != Fun
                    ? Fun(i)
                    : IndexerDefaultImpl<T>(i);
        }
    }

    public class YourClass<T>
    {
        public T this[int i] => IndexerImpl.Specializer<T>.Call(i);
    }

如果需要传入实例对返回结果进行计算,可以增加一个参数:

    internal static class IndexerImpl //non-generic static helper class
    {
        private static T IndexerDefaultImpl<T>(int i, YourClass<T> yourClass) => default(T); //default implementation

        private static T IndexerImpl2<T>(int i, YourClass<T> yourClass) => default(T); //another implementation for short/int/long

        private static string IndexerForString<T>(int i, YourClass<T> yourClass) => (i * i).ToString(); //specialization for T=string
        private static DateTime IndexerForDateTime<T>(int i, YourClass<T> yourClass) => new DateTime(i * i * i); //specialization for T=DateTime

        static IndexerImpl() //install the specializations
        {
            Specializer<string>.Fun = IndexerForString;
            Specializer<DateTime>.Fun = IndexerForDateTime;

            Specializer<short>.Fun = IndexerImpl2;
            Specializer<int>.Fun = IndexerImpl2;
            Specializer<long>.Fun = IndexerImpl2;
        }

        internal static class Specializer<T> //specialization dispatcher
        {
            internal static Func<int, YourClass<T>, T> Fun;
            internal static T Call(int i, YourClass<T> yourClass)
                => null != Fun
                    ? Fun(i, yourClass)
                    : IndexerDefaultImpl(i, yourClass);
        }
    }

    public class YourClass<T>
    {
        public T this[int i] => IndexerImpl.Specializer<T>.Call(i, this);
    }

二、泛型方法的偏特化

偏特化也是差不多的做法,只不过帮助类变成了以不需要特化的类型构成的泛型类:

    internal static class GetValueImpl<R, S>
    {
        private static T DefImpl<T>(R r, S s) => default(T);
        private static int IntRet(R r, S s) => int.MaxValue;

        internal static class Specializer<T>
        {
            internal static Func<R, S, T> Fun;
            internal static T Call(R r, S s) => null != Fun ? Fun(r, s) : DefImpl<T>(r, s);
        }

        static GetValueImpl()
        {
            Specializer<int>.Fun = IntRet;
        }
    }

    public class TestClass
    {
        public T GetValue<R, S, T>(R r, S s) => GetValueImpl<R, S>.Specializer<T>.Call(r, s);
    }

以上代码片段中,被偏特化的是 GetValue 方法中的 T 类型参数,当 T=int 的时候,实际被调用的方法就是 GetValueImpl.IntRet 方法,其他情况是 GetValueImpl.DefImpl 方法。

三、泛型类的特化

泛型类的特化没有什么好的方法,只能采用继承特化类型泛型类的方式间接实现,并且将要特化处理的成员采用虚方法或者用 new 隐藏基类方法。

偏特化泛型类也可以采用差不多的方式实现。

具体做法可以参考 stackoverflow 上的这个答案:A: C# specialize generic class

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
C#泛型
现在的netcore3.1和最新的.netframework8早已经没有当初那个被人诟病的ArrayList了,但很巧这玩意不得不说,因为它决定了C团队痛改前非,抛弃过往重新上路,上一段ArrayList案例代码。publicclassArrayList{privateobject
Stella981 Stella981
2年前
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593
Wesley13 Wesley13
2年前
C#非泛型集合和泛型集合的超级详解(转)
C泛型集合之非泛型集合类与泛型集合类的对应:ArrayList对应ListHashTable对应DictionaryQueue对应QueueStack对应StackSortedList对应SortedList 转自(https://www.cnblogs.com/cheng
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Easter79 Easter79
2年前
Thinking in java Chapter15 泛型
1与C比较2简单泛型泛型类3泛型接口4泛型方法5匿名内部类6构建复杂模型78910“泛型”意思就是:适用于许多许多的类型<h2id"1"1与C比较</h2C
Wesley13 Wesley13
2年前
Java的泛型详解(一)
Java的泛型详解(一)编写的代码可以被不同类型的对象所重用。因为上面的一个优点,泛型也可以减少代码的编写。1|2泛型的使用简单泛型类publicclassPair{privateTfirst;privateTsecond;publicPair(){firstnull;secondnull;
Wesley13 Wesley13
2年前
C++:模板类
22.模板类22.1模板类模板是泛型编程的基础,那什么是泛型编程呢?泛型编程是一种独立于任何特定数据类型编写代码的方式。C标准模板库中的数据容器、迭代器和算法,都是泛型编程的例子,它们都使用了模板的概念。比如动态数组vector是可以存放任何类型数据的容器,我们可以定义许多不同类型的vector,比如vector<int或vect
Wesley13 Wesley13
2年前
Java泛型一览笔录
1、什么是泛型?泛型(Generics)是把类型参数化,运用于类、接口、方法中,可以通过执行泛型类型调用分配一个类型,将用分配的具体类型替换泛型类型。然后,所分配的类型将用于限制容器内使用的值,这样就无需进行类型转换,还可以在编译时提供更强的类型检查。2、泛型有什么用?泛型主要有两个好处:(1)消除显