将变量发送到其他类

TBK*_*TBK 0 c#

我可以使用检查是真还是假的函数并将我的口头发送给其他课程?

我试过了:

public class Func
{
    public static bool CheckDate(string number)
    {
        string new_number = number.ToString();
        if (new_number.Length==8)
        {
           string yyyy = new_number.Substring(0, 4);
           string mm = new_number.Substring(4, 2);
           string dd = new_number.Substring(6, 2);
           return true;
        }
        else
        {
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我要发送的文字yyyy,mm,dd我的Program.cs课.

我该怎么办?

Dar*_*rov 7

不要重新发明轮子,使用DateTime.TryParseExact专门为此目的而构建的方法.在处理.NET框架中的日期时忘记正则表达式和子字符串:

public static bool CheckDate(string number, out DateTime date)
{
    return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
Run Code Online (Sandbox Code Playgroud)

现在你可以看到定义CheckDate变得有点无意义,因为它已经存在于BCL中.您只需使用它:

string number = "that's your number coming from somewhere which should be a date";
DateTime date;
if (DateTime.TryParseExact(
    number, 
    "dd/MM/yyyy", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out date
))
{
    // the number was in the correct format 
    // => you could use the days, months, from the date variable which is now a DateTime

    string dd = date.Day.ToString();
    string mm = date.Month.ToString();
    string yyyy = date.Year.ToString();
    // do whatever you intended to do with those 3 variables before
}
else
{
    // tell the user to enter a correct date in the format dd/MM/yyyy
}
Run Code Online (Sandbox Code Playgroud)

更新:

由于我在评论部分得到了一条评论,我实际上没有回答这个问题,你可以使用与我推荐的方法类似的方法.但是,请保证我永远不会写这样的代码,它只是为了说明TryXXX模式.

定义一个模型:

public class Patterns
{
    public string DD { get; set; }
    public string MM { get; set; }
    public string YYYY { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后修改CheckDate方法,以便它发送一个out参数:

public static bool CheckDate(string number, out Patterns patterns)
{
    patterns = null;
    string new_number = number.ToString();
    if (new_number.Length == 8)
    {
       Patterns = new Patterns
       {
           YYYY = new_number.Substring(0, 4),
           MM = new_number.Substring(4, 2),
           DD = new_number.Substring(6, 2)
       }
       return true;
    }
    else
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以这样使用:

string number = "that's your number coming from somewhere which should be a date";
Patterns patterns;
if (CheckDate(numbers, out patterns)
{
    string dd = patterns.DD;
    string mm = patterns.MM;
    string yyyy = patterns.YYYY;
    // do whatever you intended to do with those 3 variables before
}
else
{
    // tell the user to enter a correct date in the format dd/MM/yyyy
}
Run Code Online (Sandbox Code Playgroud)

  • 我已经更新了我的答案,以说明OP如何解决他原来的问题.但是当然你绝对不应该像我更新的答案中那样编写代码.这只是为了说明目的.您应该知道的是StackOverflow不仅仅是盲目回答问题.它是为OP提供实际尝试解决的问题的最佳替代方案.如果你们不明白这里的实际问题是什么,让我告诉你:他正在尝试将字符串解析为日期实例,如果解析成功,则使用日,月和年. (2认同)