C#泛型与常量

And*_*rew 22 c# c++ security generics templates

有没有类似于这个C++模板的东西?

template <int A>
class B
{
    int f()
    {
        return A;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想使B <1>,B <2>等的每个实例(例如元组)成为不同的类型.

Cod*_*aos 22

简短的回答是否定的.

它不适合C#泛型的方式,因为它适用于C++模板.

.net泛型不是语言功能,它们是运行时功能.运行时知道如何从特殊通用字节码中实例化泛型,与C++模板可以描述的相比,这是非常有限的.

将其与C++模板进行比较,C++模板基本上使用替换类型实例化类的整个AST.可以将基于AST的实例化添加到运行时,但它肯定比当前的泛型要复杂得多.

如果没有值类型数组(仅存在于不安全代码中)等功能,使用此类参数的递归模板实例化或模板特化也不会非常有用.

  • 好吧,在运行时(JIT).Net 进行实例化。实例化本质上是带有修改的复制。我不会那么反对 AST 和 MSIL。相似概念的不同表示。 (2认同)

小智 15

此限制的解决方法是定义一个类,该类本身公开您感兴趣的文字值.例如:

public interface ILiteralInteger
{
   int Literal { get; }
}

public class LiteralInt10 : ILiteralInteger
{
   public int Literal { get { return 10; } }
}

public class MyTemplateClass< L > where L: ILiteralInteger, new( )
{
   private static ILiteralInteger MaxRows = new L( );

   public void SomeFunc( )
   {
      // use the literal value as required
      if( MaxRows.Literal ) ...
   }
}
Run Code Online (Sandbox Code Playgroud)

用法:

var myObject = new MyTemplateClass< LiteralInt10 >( );
Run Code Online (Sandbox Code Playgroud)


Jam*_*lis 12

C#不支持像C++那样的非类型泛型参数.

C#泛型比C++模板更简单,功能更少.MSDN有一个简洁的C++模板和C#泛型之间差异列表.

  • @pst:当然 您可以将信息编码为类型.您还可以完全避免泛型并编写大量非泛型类.在任何情况下; 我添加了一个MSDN文章的链接,列出了模板和泛型之间的主要区别. (3认同)

Meh*_*dad 5

C#泛型专门用于运行时,而C++模板在编译时处理以创建一个全新的类型.鉴于此,运行时根本没有处理非类型参数的功能(它不仅仅是C#问题).