在c ++ / cli中委派差异

时间:2011-07-20 20:49:24

标签: c# c++-cli covariance contravariance

我正在将C#代码转换为C ++ / CLI,我无法理解为什么它不能编译。

我收到的错误:

void MyNamespace::Handler::DataChanged(System::Object ^,System::EventArgs ^)' : the specified function does not match the delegate type 'void (System::Object ^,System::Data::DataRowChangeEventArgs ^)'

2 个答案:

答案 0 :(得分:2)

看起来C ++和CLI不支持代理的参数方差,如C#和VB那样,请参阅this Microsoft connect bug report

作为一个解决方法,你可以在一个包装器中将你的调用包装到一个包含DataRowChangeEventArgs并调用你的处理程序的包装器中:

public ref class MyClass
{
....
public:
    void MyClass::Delegates(DataTable ^table)
    {
        Handler ^handler = gcnew Handler();
        DataRowChangeEventForwarder& forwarder = 
             gcnew DataRowChangeEventForwarder(
             new EventHandler(handler, &MyNamespace::Handler::DataChanged)));
        table->RowChanged += gcnew DataRowChangeEventHandler (forwarder, &MyNamespace::MyClass::RowChangedDelegate);
    }
 }

 public ref class DataRowChangeEventForwarder 
 {
 private:
     EventHandler^ eventHandler;
 public:
     EventForwarder(EventHandler^ eventHandler) 
     {
          this->eventHandler = eventHander;
     }

     void MyClass::RowChangedDelegate(Object ^sender, DataRowEventArgs ^arg)
     {
          handler->DataChanged(sender, arg);
     }
 }

答案 1 :(得分:0)

这是一个完整的编译就绪的bug再现(将是一个评论,但格式化将是可怕的):

public ref struct A
{
};

public ref struct B : A
{
};

public ref struct C
{
    delegate void DType(B^);
    void F(A^ a) { };
};

int main(void)
{
    C^ c = gcnew C;
    C::DType^ del = gcnew C::DType(c, &C::F);
}