将类作为参数的通用方法

时间:2016-06-28 05:57:19

标签: vb.net

我有两个不同的类,并希望在Notify函数中使用class作为参数。 ====代码======================
'邮件类通知参数

Friend Class MailClass   
         Friend NotifyHost As String   
         Friend NotifyPort As String    
End Class 

' FTP类通知参数

  Friend Class FtpClass       
    Friend NotifyHost As String     
    Friend NotifyPort As String        
    End Class     


Friend Class ProcessNotification      
    'Notify on FTP Specified Email            
     Private Sub btnMailNotiFy_Click(ByVal sender As System.Object, ByVal e As     System.EventArgs)       
    Notify (ByRef mailAccount as MailClass)      
    End Sub 

    'Notify on FTP Specified Email
    Private Sub btnFTPNotiFy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
    Notify (ByRef ftpAccount as FtpClass)
    End Sub

    ' Generic method to use for multiple class
    Private Sub Notify(NO Idea ??)
    ' ## Please Help ### 
    End Sub
End Class

如何制作Notify方法Generic?

1 个答案:

答案 0 :(得分:0)

如果内存服务,generics自2.0起就成为.Net的一部分 你在寻找这样的东西吗?

Private Sub Notify(Of T as Class)(ByVal agr as T)
' do stuff
End Sub

<强>更新

按照我们在注释中的讨论,您需要创建一个接口,该接口将指定您要在泛型方法中使用的所有属性和方法,然后将其用作通用约束:

Friend Interface IMyInrteface
    NotifyHost As String   
    NotifyPort As String  
End Interface

Private Sub Notify(Of T as IMyInrteface)(ByRef agr as T)
' do stuff
End Sub

当然,您发送给此方法的所有类都必须实现接口:

Friend Class MailClass   
    Implements IMyInrteface
    Friend NotifyHost As String   
    Friend NotifyPort As String    
End Class 

Friend Class FtpClass       
    Implements IMyInrteface
    Friend NotifyHost As String     
    Friend NotifyPort As String        
End Class