我有以下代码用于根据不同类型的身份验证类型连接ot wifi
private const string ccmp = "CCMP";
private const string wpa = "WPA_PSK";
private const string tkip = "TKIP";
if (!string.IsNullOrWhiteSpace(password))
{
if (encryption == ccmp)
{
if (authenticationType == wpa)
{
var profile = string.Format(Constants.WPAPSK_PROFILE, profileName, ssidHex, password);
ConnectToWifi(profileName, wlanIface, profile);
}
else
{
var profile = string.Format(Constants.WPA2_PROFILE, profileName, ssidHex, password);
ConnectToWifi(profileName, wlanIface, profile);
}
}
else if (encryption == tkip)
{
if (authenticationType == wpa)
{
var profile = string.Format(Constants.TKIPWPA_PROFILE, profileName, ssidHex, password);
ConnectToWifi(profileName, wlanIface, profile);
}
else
{
var profile = string.Format(Constants.TKIPWPA2_PROFILE, profileName, ssidHex, password);
ConnectToWifi(profileName, wlanIface, profile);
}
}
else
{
try
{
var existingProfile = wlanIface.GetProfileXml(profileName);
if (existingProfile != null)
{
wlanIface.DeleteProfile(profileName);
}
}
catch (Exception e)
{
var ex = e;
}
var profile = string.Format(Constants.WEP_PROFILE, profileName, ssidHex, password);
ConnectToWifi(profileName, wlanIface, profile);
}
}
private void ConnectToWifi(string profileName, WlanClient.WlanInterface wlanIface, string profile)
{
new Thread(() =>
{
try
{
wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profile, true);
wlanIface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Infrastructure, profileName, 5000);
SpinWait.SpinUntil(() => Networking.IsNetworkConnected(), 5000);
}
catch (Exception e)
{
var ex = e;
}
finally
{
Dispatcher.BeginInvoke(new Action(() => { CheckStatus(); }));
}
}).Start();
}
它显然处于工作模式,但代码似乎有点冗长和复杂。 如何使用Factory模式优化代码?