2013-05-15 33 views
0

我試圖在C++/CLI中實現一個抽象的C#類。這個抽象基類已經實現INotifyPropertyChanged的,並提到用C#編寫:C++/CLI:實現一個抽象的C#類,實現INotifyPropertyChanged結果在C++編譯器錯誤C3766

public abstract class BaseClass : INotifyPropertyChanged 

在C++/CLI裝配,我確實有實現INotifyPropertyChanged另一個接口:

public interface class IAnotherNotifyPropertyChangedClass : public INotifyPropertyChanged 

現在,繼承時抽象C#類BaseClass的貫徹IAnotherNotifyPropertyChangedClass在C++/CLI我得到如下:

public ref class AnotherNotifyPropertyChangedClass : public BaseClass, public IAnotherNotifyPropertyChangedClass 

這就導致在下面的編譯錯誤:

error C3766: 'AnotherNotifyPropertyChangedClass' must provide an implementation for the interface method 'void System::ComponentModel::INotifyPropertyChanged::PropertyChanged::add(System::ComponentModel::PropertyChangedEventHandler ^)' 

只要我刪除了INotifyPropertyChanged的從IAnotherNotifyPropertyChangedClass接口聲明,一切編譯罰款。這是爲什麼?這個聲明在使用C#時會很好地編譯。我使用VS 2012並編譯.NET 3.5混合模式程序集。

在此先感謝!

乾杯!

編輯: 類似的問題(沒有C#)在這裏:http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/3047b8d1-348c-4ca6-b3f3-c396c03fedf7/ 所以這是C++/CLI的設計?

回答

1

這是因爲interafce需要像實施:

#region INotifyPropertyChanged Members 
public event PropertyChangedEventHandler PropertyChanged; 
#endregion 

因爲C#類是抽象的不(要)照顧這一點,你需要實現它在你的C++類。這是第一個不抽象的類。

+0

用C#編寫的抽象類實現了接口。在純C#中執行相同的場景(聲明另一個繼承INotifyPropertyChanged並在基類頂部實現它的接口)就像一個魅力... – barnacleboy

+0

我試圖說如果有兩個INotifyPropertyChanged的實現。這與公共IEnumerator GetEnumerator()和IEnumerable.GetEnumerator()類似,您需要兩者均可用。 –

2

你需要做的是在你的C++/CLI類中有一個INotifyPropertyChanged的顯式實現。你可以讓它調用已經實現的C#版本。

我不是100%確定在您的情況下,您可能不得不明確實施AnotherNotifyPropertyChangedClass::PropertyChanged而不是INotifyPropertyChanged::PropertyChanged

private: 
    event PropertyChangedEventHandler^ DuplicatePropertyChanged 
    { 
     virtual void add (PropertyChangedEventHandler^ value) sealed = 
      INotifyPropertyChanged::PropertyChanged::add 
     { 
      // Add to the event defined in the C# class. 
      this->PropertyChanged += value; 
     } 

     virtual void remove (PropertyChangedEventHandler^ value) sealed = 
      INotifyPropertyChanged::PropertyChanged::remove 
     { 
      // Remove from the event defined in the C# class. 
      this->PropertyChanged -= value; 
     } 
    } 
+0

我明白你的觀點。這只是做了編譯器希望我做的事情,但爲什麼在C#中實現C++/CLI類時這不是必需的? – barnacleboy

3

這是不正常的,我沒有得到這個repro。這個問題不顯示實際的代碼,我會告訴我的:

C#的測試類:

using System.ComponentModel; 

namespace ClassLibrary8 { 
    public abstract class CFoo : INotifyPropertyChanged { 
     public event PropertyChangedEventHandler PropertyChanged; 
    } 
} 

的C++/CLI測試代碼,其添加到C#項目的引用後:

using namespace System::ComponentModel; 

public interface class IBar : public INotifyPropertyChanged { 
}; 

public ref class Baz : ClassLibrary8::CFoo, IBar { 
    // fine 
}; 
+0

這正是我實現這些類的方式。唯一的區別是CFoo需要一個類型參數並且讀取「CFoo 」。在純C中執行C++/CLI代碼時,一切都按預期工作。你也使用VS2012和3.5嗎? – barnacleboy

+0

我可以嘗試再次複製。但是,如果還有另一個你沒有提到的細節,這可能會再次浪費我的時間。您*必須*發佈[SSCCE代碼片段](http://sscce.org/),以顯示問題以獲得幫助。 –