当T实现类</t>时,C ++ / CLI中的IComparable <t>

时间:2011-05-27 22:14:19

标签: c# .net generics c++-cli

更新:如评论中所述,C ++ / CLI应该是value struct;编译错误'明确'陈述“必须是值类型”。


在C#中,我可以写

      public struct Id<T> : IComparable<Id<T>>
    {
        public int CompareTo(Id<T> other)
        {
            throw new NotImplementedException();
        }
    }

当我尝试在C ++ / CLI中执行相同操作时

generic<typename T>
public ref struct Id : System::IComparable<Id<T>>
{
public:
    virtual int CompareTo(Id<T> other)
    {
        throw gcnew System::NotImplementedException();
    }
};

我收到编译错误error C3225: generic type argument for 'T' cannot be '...::Id<T>', it must be a value type or a handle to a reference type

是否this编译器错误仍然没有修复?

2 个答案:

答案 0 :(得分:5)

在C ++ / CLI中,您需要在托管类型上使用句柄。这编译:

generic<typename T>
public ref struct Id : System::IComparable<Id<T>^>
{
public:
    virtual int CompareTo(Id<T>^ other)
    {
        throw gcnew System::NotImplementedException();
    }
};

答案 1 :(得分:2)

如评论中所述; C#的struct的C ++ / CLI等价物是value struct,而不是ref struct