使用C# UdpClient时,想判断当前的UDP连接是否可用,并发送数据,发现封装有protected 属性Active。使用反射实现了访问对于该属性的访问。
public class UDPTest : UdpClient//继承UdpClient
{
public UdpClient udpClient = new UdpClient();//实例化
public bool IsActive()// 封装public方法 使用反射访问Active属性(可进一步封装为public属性)
{
const BindingFlags InstanceBindFlags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = udpClient.GetType();
PropertyInfo res = type.GetProperty("Active", InstanceBindFlags);
var value = res.GetValue(udpClient, null);
return Convert.ToBoolean(value);
}
}