C#中不使用Main方法运行Luhn算法代码的方法及位置疑问
关于Luhn算法代码无Main方法运行的问题
首先明确:.NET控制台应用必须要有入口点(Main方法),你看到的网上示例没写Main,是因为那些代码是**类库项目(Class Library)**的一部分——类库是用来被其他程序引用的工具代码,本身不需要独立运行,所以不需要入口点。
你的问题解决方案分两种场景:
1. 想独立运行测试代码(需要入口)
Main方法可以放在同一个命名空间下的单独类中(推荐,保持Luhn类的职责单一),或者直接加到Luhn类里(不推荐)。另外注意:你原代码里的IsValid是static但没加public,外部无法调用,必须改成public。
示例代码(单独入口类):
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace LuhnAlgorithm { public static class Luhn { // 改为public,允许外部调用 public static bool IsValid(string number) { if (string.IsNullOrEmpty(number)) return false; bool onSecondDigit = false; int count = 0; int sum = 0; for (int i = number.Length - 1; i >= 0; i--) { char c = number[i]; if (!char.IsDigit(c)) { if (c == ' ') continue; return false; } int digit = c - '0'; if (onSecondDigit) { digit *= 2; if (digit > 9) digit -= 9; } sum += digit; count++; onSecondDigit = !onSecondDigit; } return count > 1 && sum % 10 == 0; } } // 独立的入口类,存放Main方法 class Program { static void Main(string[] args) { // 测试示例 string testCard = "4111 1111 1111 1111"; bool isValid = Luhn.IsValid(testCard); Console.WriteLine($"卡号 {testCard} 有效性:{isValid}"); } } }
如果你用的是C# 9及以上版本,可以用顶级语句,不用显式写Main——编译器会自动帮你生成入口点,代码更简洁:
using System; namespace LuhnAlgorithm { public static class Luhn { public static bool IsValid(string number) { // 你的原逻辑不变 if (string.IsNullOrEmpty(number)) return false; bool onSecondDigit = false; int count = 0; int sum = 0; for (int i = number.Length - 1; i >= 0; i--) { char c = number[i]; if (!char.IsDigit(c)) { if (c == ' ') continue; return false; } int digit = c - '0'; if (onSecondDigit) { digit *= 2; if (digit > 9) digit -= 9; } sum += digit; count++; onSecondDigit = !onSecondDigit; } return count > 1 && sum % 10 == 0; } } } // 顶级语句,直接写测试逻辑,无需显式Main string testCard = "49927398716"; bool result = LuhnAlgorithm.Luhn.IsValid(testCard); Console.WriteLine($"测试结果:{result}");
2. 不想写Main,仅作为工具类使用
把项目改成类库项目(Class Library),然后通过单元测试来验证IsValid方法的正确性,完全不需要Main方法。
比如用xUnit写测试(需先在NuGet安装xUnit和xUnit.runner.visualstudio):
using Xunit; using LuhnAlgorithm; namespace LuhnTests { public class LuhnValidationTests { [Fact] public void ValidCard_ReturnsTrue() { Assert.True(Luhn.IsValid("4111111111111111")); } [Fact] public void InvalidCard_ReturnsFalse() { Assert.False(Luhn.IsValid("4111111111111112")); } [Fact] public void CardWithSpaces_ReturnsTrue() { Assert.True(Luhn.IsValid("4111 1111 1111 1111")); } } }
内容的提问来源于stack exchange,提问作者Y0sh1
相关产品推荐
相关产品推荐

