Cod*_*aos 22
简短的回答是否定的.
它不适合C#泛型的方式,因为它适用于C++模板.
.net泛型不是语言功能,它们是运行时功能.运行时知道如何从特殊通用字节码中实例化泛型,与C++模板可以描述的相比,这是非常有限的.
将其与C++模板进行比较,C++模板基本上使用替换类型实例化类的整个AST.可以将基于AST的实例化添加到运行时,但它肯定比当前的泛型要复杂得多.
如果没有值类型数组(仅存在于不安全代码中)等功能,使用此类参数的递归模板实例化或模板特化也不会非常有用.
小智 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#泛型之间的差异列表.
| 归档时间: |
|
| 查看次数: |
8286 次 |
| 最近记录: |