这里提供了一种方法,可以根据国际电话号码获取国家信息,而不需要使用Google库。
首先,让我解释一下为什么很难确定所在的国家。有些国家的国家代码只有1、2、3或4位数字,这本来很简单。但是,国家代码1不仅用于美国,还用于加拿大和其他一些小地方:
1339 美国
1340 维京群岛(加勒比海岛屿)
1341 美国
1342 未使用
1343 加拿大
数字2到4决定它是否为美国、加拿大等。没有简单的方法可以确定国家,例如前三个数字是加拿大,后面的是美国。
对于我的代码,我定义了一个类,保存每个数字的信息。
public class DigitInfo {
public char Digit;
public Country? Country;
public DigitInfo?[]? Digits;
}
第一个数组保存了数字中的第一个数字的DigitInfos。第二个数字用作DigitInfo.Digits的索引。沿着该Digits链向下移动,直到Digits为空为止。如果定义了Country(即不为null),则返回该值,否则返回之前定义的任何Country:
country code 1: byPhone[1].Country is US
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since
byPhone[1].Country is US, also 1235 is US, because no other
country was found in the later digits
这是一个根据电话号码返回国家的方法:
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
if (phoneNumber.Length==0) return null;
var isFirstDigit = true;
DigitInfo? digitInfo = null;
Country? country = null;
foreach (var digitChar in phoneNumber) {
var digitIndex = digitChar - '0';
if (isFirstDigit) {
isFirstDigit = false;
digitInfo = ByPhone[digitIndex];
} else {
if (digitInfo!.Digits is null) return country;
digitInfo = digitInfo.Digits[digitIndex];
}
if (digitInfo is null) return country;
country = digitInfo.Country??country;
}
return country;
}
其余的代码(世界各国的digitInfos,测试代码等)太大了,无法在此处发布,但可以在Github上找到:
https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsHelperLib/CountryCode.cs
该代码是WPF TextBox的一部分,该库还包含其他控件,用于电子邮件地址等。更详细的描述在CodeProject上:
详细解释国际电话号码验证
更改23.1.23:我将CountryCode.cs移动到WpfWindowsHelperLib中,尽管它的名称如此,但它没有任何WPF依赖项。