2015-10-28 114 views
1

有一些我正在使用的VB代碼。我從原來的VB代碼重寫一些事情,在C#c#在屬性上實現接口

我的VB類的內部:

Implements actionBaseClass 

    Private m_config_url As String 
    Private m_config_unc As String 
    Private m_connection_string As String 
    Private m_xml_doc_path_or_data As String 
    Private m_fpid As String 
    Private m_cancelled As Boolean 
    Private m_xml_doc_element As Xml.XmlElement 
    Private m_removing As Boolean 
    Private m_xml_doc As New Xml.XmlDocument 


    Property XMLDocPathOrData() As String Implements actionBaseClass.XMLDocPathOrData 
     Get 
      XMLDocPathOrData = m_xml_doc_path_or_data 
     End Get 
     Set(ByVal Value As String) 
      m_xml_doc_path_or_data = Value 
     End Set 
    End Property 

    WriteOnly Property FPId() As String Implements actionBaseClass.FPId 
     Set(ByVal Value As String) 
      m_fpid = Value 
     End Set 
    End Property 

我已轉化的C#接口:

interface actionBaseClass 
{ 

    public bool UseStringData { get; } 
    string XMLDocPathOrData { get; set; } 
    string FPId { set; } 
    string ConfigURL { set; } 
    string ConfigUNC { set; } 
    string ConnectionString { set; } 
    bool Cancelled { get; } 
    void ActionMe(); 
    void DisposeMe(); 

} 

我已轉化的C#類到目前爲止:

public partial class Form1 : Form, actionBaseClass 
    { 


     #region Public Implements from base class 

     private string m_config_url, m_config_unc, m_connection_string, m_xml_doc_path_or_data, m_fpid; 
     private bool m_cancelled, m_removing; 
     private XmlElement m_xml_doc_element; 
     private new XmlDocument m_xml_doc; 

     public bool UseStringData 
     { 
      get { return false; } 
     } 


     public string XMLDocPathOrData 

     { 
      get { return actionInterface.XMLDocPathOrData = m_xml_doc_path_or_data; } 
      set { m_xml_doc_path_or_data = value; } 
     } 

     public string FPId 
     { 
      set { m_fpid = value; } 
     } 

如何在C#中使用上述VB代碼中的屬性聲明中的Implements?或者你沒有在C#中使用Implements <interface_name>

+0

檢查[這篇文章](http://www.codeproject.com/Articles/1000374/Explicit-Interface-VS-Implicit-Interface-in-Csharp) –

+0

據我所知,你已經這樣做隱式,這裏'公共部分類Form1:Form,actionBaseClass'。 – rotgers

回答

1

如果你已經實現你的類接口,然後用相同的簽名屬性會自動隱含實現後的界面。如果你想明確實現接口,你也可以做到這一點。

bool actionBaseClass.UseStringData { 
     get { 
      Console.WriteLine("actionBaseClass.UseStringData was called"); 
      return this.UseStringData; // call through to the other declared property 
     } 
    } 
+0

這是正確的,但作爲一些額外的信息,如果你想明確地實現一個接口屬性,你將接口名稱添加到屬性名稱中:'public int ISomeInterface.SomeProperty {get {return 1; }}。 – Moho

+0

@莫霍:是的,我正在研究這個。 :-) – StriplingWarrior

+0

@Moho,你不能在一個顯式實現的成員上指定一個訪問修飾符 –

2

您不必在C#中爲每個實現接口實現的屬性和方法指定一個Implements關鍵字。只要簽名匹配,編譯器就知道該屬性或方法是來自接口的實現。您的代碼

另外兩個注意事項:

  1. 的約定是該接口的名稱以大寫我做起,像IAction
  2. 使用PascalCase類和接口名稱
  3. 如果它是一個接口,是沒有意義,它被稱爲「BaseClass」
  4. 您不必指定公共屬性和接口中的方法(請參閱UseStringData)