2012-05-06 151 views
2

有一個類和一個代表C#麻煩與代表

public delegate void Super(); 
public class Event 
{ 
    public event Super activate ; 
    public void act() 
    { 
     if (activate != null) activate(); 
    } 
} 

和C++/CLI

public delegate void Super(); 
public ref class Event 
{ 
public: 
    event Super ^activate; 
    void act() 
    { 
     activate(); 
    } 
}; 
在C#

創建在這樣的(方法Setplus和setminus)

類多播委託
public class ContainerEvents 
{ 
    private Event obj; 
    public ContainerEvents() 
    { 
     obj = new Event(); 
    } 
    public Super Setplus 
    { 
     set { obj.activate += value; } 
    } 
    public Super Setminus 
    { 
     set { obj.activate -= value; } 
    } 
    public void Run() 
    { 
     obj.act(); 
    } 
} 

但在C++/Cli中出現錯誤 - usage requires Event::activate to be a data member

public ref class ContainerEvents 
{ 
    Event ^obj; 
public: 
    ContainerEvents() 
    { 
     obj = gcnew Event(); 
    } 
    property Super^ Setplus 
    { 
     void set(Super^ value) 
     { 
      obj->activate = static_cast<Super^>(Delegate::Combine(obj->activate,value)); 
     } 
    } 

    property Super^ SetMinus 
    { 
     void set(Super^ value) 
     { 
      obj->activate = static_cast<Super^>(Delegate::Remove(obj->activate,value)); 
     } 
    } 

    void Run() 
    { 
     obj->act(); 
    } 
}; 

問題在哪裏?

回答

2

參見:http://msdn.microsoft.com/en-us/library/ms235237(v=vs.80).aspx

C++/CLI遵循相同的模擬爲C#。這將是非法的C#來定義的:

public Super Setplus 
{ 
    set { obj.activate = Delegate.Combine(obj.activate, value); } 
} 

這是C++/CLI相同。使用現代語法中定義的+ =/- =表示法。

property Super^ Setplus 
{ 
    void set(Super^ value) 
    { 
     obj->activate += value; 
    } 
}