Typedefs,C ++ / CLI,C#+依赖注入

时间:2013-05-31 13:11:20

标签: c# c++ dependency-injection c++-cli

我有一个用C#编写的专用字典,它带有两个泛型参数。界面是

public interface IMyDictionary<TKey, TValue> { ... }

和其中一个实现

public MyDictionary<TKey, TValue> {...}

我还有一个复杂的C ++模板结构,我在C ++ / CLI ref类中输入:

typedef boost::some_complex_template<stuff>    MySimpleValueType;

在我的C ++ / CLI ref类构造函数中,我曾经创建了一个字典实例:

MyCppCliClass::MyCppCliClass()
    : _my_dict(gcnew MyDictionary<MySimpleValueType, Something^>())
{...}

现在,如果你喜欢依赖注入,你会发现这很糟糕。理想情况下,我应该有这样的构造函数:

MyCppClass::MyCppCliClass(IMyDictionary<MySimpleValueType, Something^>^ dict){...}

这个类在C#中实例化,所以现在我的问题是:

我如何在C ++ / CLI之外实例化我正在使用的这个有效的ref类,因为(afaik)C ++模板typedef和C#中都没有纯C ++类型?

MySimpleValueType显然必须是C#的本机类型,否则Dictionary的实例化将失败:

error C3225: generic type argument for 'T1' cannot be '...', it must be a value type
> or a handle to a reference type.

我觉得我应该能够在C ++ / CLI类中定义类型(使用typedef),但是从外部实例化Dictionary。 C#中没有C ++ / CLI typedef,所以也许有一种方法可以获得var的getter和类型推导?有什么想法吗?

1 个答案:

答案 0 :(得分:0)

boost是一个无人值守的库。该错误消息告诉您不能在通用托管类中使用非托管类型。

要解决此问题,请创建一个托管类来保存您的非托管类,并在容器中使用它。

public ref class MySimpleValueTypeHolder
{
private:
    MySimpleValueType* unmanaged;

public:
    property MySimpleValueType* ValueType { 
        MySimpleValueType* get() { return this->unmanaged; }
    }

    MySimpleValueTypeHolder() { this->unmanaged = new MySimpleValueType(); }
    ~MySimpleValueTypeHolder() { this->!MySimpleValueTypeHolder(); }

    !MySimpleValueTypeHolder()
    {
        if(this->unmanaged != nullptr)
        {
            delete this->unmanaged;
            this->unmanaged = nullptr;
        }
    }
};

Dictionary<MySimpleValueTypeHolder^, Something^>^ foo;