我如何检查字符串以查看所有字符是否都是整数,长度是否为8个字符,并为每个字符都加一个参数?

问题描述 投票:0回答:1

班级学生和主要学生仅供参考。在try catch块中有两个单独的s1.SNum =“ string”,每个应该抛出一个单独的参数,但是每次都抛出相同的参数,而我不知道出来。

class Student
    {
       public string FirstName { get; private set; }
       public string LastName { get; private set; }
       public Date BirthDate { get; private set; }

       public Date catalog;
       public string sNum;
     }

这是我遇到麻烦的代码。我想拥有两个抛出sNum异常的集合。一种表示没有全数字,另一种表示没有八位数字。

public string SNum
        {
            get
            {
                return sNum;
            }

            set
            {
            foreach (char c in sNum)
            {
                int count = 0;
                char charToCount = ',';
                bool result = (SNum.All(Char.IsDigit));

                if (result == false)
                {
                    throw new ArgumentOutOfRangeException(nameof(SNum), value,
                    $"{nameof(SNum)} characters are not all integers.");
                }

                if (c == charToCount)
                {
                    count++;
                }
                else if (count != 8)       BOTH WILL THROW THIS ARGUMENT RIGHT NOW
                {
                    throw new ArgumentOutOfRangeException(nameof(SNum), value,
                    $"{nameof(SNum)} length is not eight.");
                }
            }
        }

和用于尝试捕获的主类。即使我正在检查任何字母,s1.SNum = "158945K9";仍会抛出与s1.SNum = "1234567";相同的异常

            // attempt to assign invalud sNum length
            try
            {
                s1.SNum = "1234567";  
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine($"{ex.Message}\n");
            }

            // attempt to assign invalud sNum character
            try
            {
                s1.SNum = "158945K9";
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine($"{ex.Message}\n");
            }
c# class object linq-to-objects
1个回答
0
投票

如果您只关心值是所有数字并且长8个字符,则实现比您要简单得多:

© www.soinside.com 2019 - 2024. All rights reserved.