public static bool IsValidCreditCard(string cardNumber)
{
if(cardNumber.Length!=16)
{
throw new Exception("卡号不是16位");
}
int oddSum = 0;
int evenSum = 0;
List list = cardNumber.ToCharArray().Reverse().ToList();
for (int i = 1; i < list.Count + 1; i++)
{
if (!char.IsDigit(list[i - 1]))
{
throw new Exception("卡号包含非法字符");
}
int item = (int)char.GetNumericValue(list[i - 1]);
if (i % 2 == 0)
{
//even index
int num = item * 2;
evenSum += num > 9 ? num.ToString().ToCharArray().Sum(ch =>
{
return (int)char.GetNumericValue(ch);
}) : num;
}
else
{
//odd index
oddSum += item;
}
}
return (oddSum + evenSum) % 10 == 0;
}