Skip to main content
 首页 » 编程设计

c#之C++ CLR 托管 DLL,包含要在 C# 中使用的模板类

2024年02月13日11sharpest

这是我的 dll 中的模板类之一:

template <class Type> 
public ref class linkedList { 
protected: 
    nodeType<Type>^ head; 
    nodeType<Type>^ tail; 
 
public: 
    linkedList(); 
    linkedList(const nodeType<Type>^newHead); 
 
    nodeType<Type>^ getHead() { return head; } 
    nodeType<Type>^ getTail() { return tail; } 
    void push(const Type item); 
    Type pop(); 
 
    bool isEmpty(); 
 
    void refreshTail(); 
    void print(); 
    void destroy(); 
    void appendToTail(nodeType<Type>^const newNode); 
    ~linkedList(); 
}; 

这已经定义好了。但是,当我引用 dll 时,它的命名空间没有显示。 我尝试像这样添加一个非模板类:

    public ref class number{ 
private: int x; 
public: void exFunction(int y){ x=y;} 
}; 

然后出现命名空间。假设命名空间是“MP”,我使用“using MP;”在 C# 中。 这样,我就可以调用 exFunction,但不能调用其他类,它们是模板类。如何调用模板类?

请您参考如下方法:

在您的 C++/CLI dll 中,使用“generic”代替:

generic<class Type> 
public ref class linkedList 

关于此的一些说明:C++/CLI 允许"template"和“泛型”-"template"的工作方式类似于典型的 native C++ 模板,而“泛型”的工作方式类似于 C# 中的泛型。