在C#中使用C++ CLI模板类

Aut*_*act 9 .net c# c++-cli

我在C++/CLI中有以下类和int原语的显式模板实例化.

template<typename T>
public ref class Number
{
    T _value;
public:
    static property T MinValue
    {
        T get()
        {
            return T::MinValue;
        }
    }

    static property T MaxValue
    {
        T get()
        {
            return T::MaxValue;
        }
    }

    property T Value
    {
        T get()
        {
            return _value;
        }

        void set(T value)
        {
            if( value<MinValue || value > MaxValue)
                throw gcnew System::ArgumentException("Value out of range");

            _value = value;
        }
    }

};

template ref class Number<int>;
Run Code Online (Sandbox Code Playgroud)

在编译它并使用反射器检查生成的程序集时,我能够看到一个被调用的类,Number<int>但在尝试在C#中实例化这个相同的类时,编译器会抱怨某些System::Number类没有采用模板参数.我究竟做错了什么?这可以完成吗?

Aut*_*act 12

我有一个解决方法,声明一个继承Number<int>该类的附加类.此类现在在C#中可见,并且可以实例化.

public ref class MyInt32 : public Number<int>
{
};
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 10

反射器在这里了一点.该类的名称实际上不是Number <int>.它实际上是'Number <int>'.注意单引号.这些只有在使用ildasm查看类型名称时才可见.

相信这样做是为了使类型在大多数语言中不可绑定,因为它们无法理解C++模板的实际工作方式.这使得它实际上只对C++编译器可见,这是合适的,因为它是唯一实际支持模板的MS编译器(templates!= generics).