C#泛型与常量 [英] C# generic with constant

查看:114
本文介绍了C#泛型与常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 模板< int A>类似于这个C ++模板吗? 
class B
{
int f()
{
return A;
}
}

我想让每个B< 1> ,B 2等等(例如元组)不同的类型。 解决方案

简短的答案是 strong>。



它不适合C#泛型,就像C ++模板一样。



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



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



没有像值类型数组(只存在于不安全的代码中),使用这些参数的递归模板实例化或模板特化也不会很有用。


Is there something similar to this C++ template?

template <int A>
class B
{
    int f()
    {
        return A;
    }
}

I want to make every instance of B<1>, B<2>, etc (eg tuple) a different type.

解决方案

The short answer is no.

It doesn't fit the way C# generics, as apposed to C++ templates, work.

The .net generics are not a language feature, they are a runtime feature. The runtime knows how to instantiate generics from special generic bytecode which is rather restricted compared to what C++ templates can describe.

Compare this with C++ templates, which basically instantiate the whole AST of the class using substituted types. It'd be possible to add AST based instantiation to the runtime, but it'd certainly be much more complex than the current generics.

Without features like value-type arrays (which only exist in unsafe code), recursive template instantiation or template specialization using such parameters wouldn't be very useful either.

这篇关于C#泛型与常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆