gpt4 book ai didi

c# - 如何使用单独的类在 C# 中验证信用卡号

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:18 25 4
gpt4 key购买 nike

我已经设置了一个类来验证信用卡号。信用卡类型和号码在单独类别的表格上选择。我正在尝试弄清楚如何将在其他类 (frmPayment) 中选择的信用卡类型和号码添加到我的信用卡类算法中:

public enum CardType
{
MasterCard, Visa, AmericanExpress
}

public sealed class CardValidator
{
public static string SelectedCardType { get; private set; }
public static string CardNumber { get; private set; }

private CardValidator(string selectedCardType, string cardNumber)
{
SelectedCardType = selectedCardType;
CardNumber = cardNumber;
}

public static bool Validate(CardType cardType, string cardNumber)
{
byte[] number = new byte[16];


int length = 0;
for (int i = 0; i < cardNumber.Length; i++)
{
if (char.IsDigit(cardNumber, i))
{
if (length == 16) return false;
number[length++] = byte.Parse(cardNumber[i]); //not working. find different way to parse
}
}

switch(cardType)
{
case CardType.MasterCard:
if(length != 16)
return false;
if(number[0] != 5 || number[1] == 0 || number[1] > 5)
return false;
break;

case CardType.Visa:
if(length != 16 & length != 13)
return false;
if(number[0] != 4)
return false;
break;

case CardType.AmericanExpress:
if(length != 15)
return false;
if(number[0] != 3 || (number[1] != 4 & number[1] != 7))
return false;
break;

}

// Use Luhn Algorithm to validate
int sum = 0;
for(int i = length - 1; i >= 0; i--)
{
if(i % 2 == length % 2)
{
int n = number[i] * 2;
sum += (n / 10) + (n % 10);
}
else
sum += number[i];
}
return (sum % 10 == 0);

}

最佳答案

您正在错失更好的 OOP 和更简洁的代码的绝佳机会。

class CreditCard
{
public CreditCard(string number, string expiration, string cvv2) {...}

public virtual bool IsValid()
{
/* put common validation logic here */
}

/* factory for actual cards */
public static CreditCard GetCardByType (CardType card, string number, string expiration, string cvv2)
{
switch (card)
{
case CardType.Visa:
return new VisaCreditCard(...);

...
}
}
}

class VisaCreditCard : CreditCard
{
public VisaCreditCard (string number, string expiration, string cvv2 )
: base (number, expiration, cvv2)
{...}

public override bool IsValid()
{
/* check Visa rules... */
bool isValid = ...

return isValid & base.IsValid();
}
}

关于c# - 如何使用单独的类在 C# 中验证信用卡号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2814446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com