下面的示例说明一个使用受保护属性 Active 的派生类。在该示例中,MyTcpClientDerivedClass 验证在获取基础 Socket 之前连接是否是活动的。
[Visual Basic]
' This derived class demonstrates the use of three protected properties belonging to the TcpClient Class.
Public Class MyTcpClientDerivedClass
Inherits TcpClient
Public Sub New()
End Sub 'New
Public Sub UsingProtectedMethods()
'Uses the protected 'Active' property belonging to the TcpClient base class
'to determine if a connection is established.
If Me.Active Then
' Calls the protected 'Client' property belonging to the TcpClient base class.
Dim s As Socket = Me.Client
'Uses the Socket returned by Client to set an option that is not available using TcpClient.
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1)
End If
'To free all resources, calls protected virtual method Dispose belonging to the TcpClient base class.
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub 'UsingProtectedMethods
End Class 'MyTcpClientDerivedClass
[C#]
// This derived class demonstrates the use of three protected methods belonging to the TcpClient class
public class MyTcpClientDerivedClass : TcpClient{
// Constructor for the derived class.
public MyTcpClientDerivedClass() : base(){
}
public void UsingProtectedMethods(){
// Uses the protected 'Active' property belonging to the TcpClient base class
// to determine if a connection is established.
if (this.Active){
// Calls the protected 'Client' property belonging to the TcpClient base class.
Socket s = this.Client;
// Uses the Socket returned by Client to set an option that is not available using TcpClient.
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
// To free all resources, calls the protected virtual method Dispose belonging to the TcpClient base class.
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
[JScript]
// The purpose of this class is to demonstrate the use of three protected methods belonging to the TcpClient Class
public class MyTcpClientDerivedClass extends TcpClient{
// constructor
public function MyTcpClientDerivedClass(){
super();
}
public function importProtectedMethods(){
//Use the protected property 'Active' belonging to the TcpClient base class.
//This determines if connection is established.
if (this.Active){
//Calling the protected property 'client' belonging to the TcpClient base class.
var s : Socket = this.Client;
//Suppose you want to set an option that is not available by just import TcpClient object.
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
//Call protected virtual method Dispose belonging to the TcpClient base class to free all resources.
this.Dispose(true);
GC.SuppressFinalize(this);