代码之家  ›  专栏  ›  技术社区  ›  Icemanind

从转换接口实现VB.NET版至C#

  •  3
  • Icemanind  · 技术社区  · 15 年前

    这似乎是一个显而易见的答案,但我似乎找不到答案。我有这个密码VB.NET版:

    Public Interface ITestInterface
        WriteOnly Property Encryption() As Boolean
    End Interface
    

    Partial Public Class TestClass
        Implements ITestInterface
    
        Public WriteOnly Property EncryptionVB() As Boolean Implements ITestInterface.Encryption
            Set(ByVal value As Booleam)
                 m_Encryption = value
            End Set
        End Property
    End Class
    

    我想把它转换成C。我把C#接口转换得很好,就像这样:

    public interface ITestInterface
    {
        bool Encryption { set; }
    }
    

    问题是,如何转换实现。我有这个:

    public partial class TestClass
    {
        public bool Encryption 
        {
             set { m_Encryption = value; }
        }
    }
    

    问题是,在C#中,似乎必须将函数命名为与正在实现的接口函数相同的名称。如何调用此方法EncryptionVB而不是Encryption,但仍然实现Encryption属性?

    5 回复  |  直到 15 年前
        1
  •  5
  •   Dan Tao    15 年前

    我能想到的最接近的方法是使用显式实现:

    public partial class TestClass : ITestInterface
    {
        public bool EncryptionVB
        {
             ((ITestInterface)this).Encryption = value;
        }
    
        bool ITestInterface.Encryption { set; }
    }
    

    现在,表面上看,这似乎是“不一样的事情”,但实际上是。考虑到这样一个事实VB.NET版,当您为实现接口成员的成员命名与接口定义不同的名称时,此“新名称”仅在您在编译时知道类型时才会出现。

    所以:

    Dim x As New TestClass
    x.EncryptionVB = True
    

    x 在上面的代码中输入为 ITestInterface ,那个 EncryptionVB 属性将不可见。只有在 Encryption :

    Dim y As ITestInterface = New TestClass
    y.Encryption = True
    

    实际上,这是一种行为 完全一样

    TestClass x = new TestClass();
    x.EncryptionVB = true;
    
    ITestInterface y = new TestClass();
    y.Encryption = true;
    
        2
  •  4
  •   Jordão    15 年前

    C#不支持接口成员别名VB.NET版.

    最好的搭配是这样的:

    public partial class TestClass : ITestInterface{
      bool ITestInterface.Encryption {
        set { m_Encryption = value; }
      }
    
      public bool EncryptionVB {
        set { ((ITestInterface)this).Encryption = value; }
      }
    }
    
        3
  •  2
  •   Joel Etherton    15 年前

    public bool EncryptionVB {
        set { m_Encryption = value; }
    }
    bool ITestInterface.Encryption {
        set { EncryptionVB = value; }
    }
    
        4
  •  0
  •   Oded    15 年前

    这在C#中是不可能的—在实现接口时,成员 在接口中定义名称。

        5
  •  0
  •   abhishek    15 年前

    VB.NET版有很多功能,很少有不完全遵循OOPS的。其中之一就是这个。