C#谜语;使用 DateTime 作为方法参数和空构造函数从潜在雇主进行测试

C# riddle; test from potential employer with DateTime as method parameter, and empty constructor

一个潜在的雇主给我发了下面的代码,只是说它包含一些问题,需要重写才能正常工作。没有给出上下文。

1.  class DateEx
2.   static INT hasFormatted == false
3.   public dateEx(){}
4.   public string formatDate( DateTime myDate=null ) {
5.       if hasFormatted = true
6.         return "The date "myDate" is already formatted.";
7.       else
8.          return string.format("{0:m/d/yyyy}"  myDate);
9.       }
10.      return myDate;
11.   }

我将其识别为 C#,但无法弄清楚此处的含义或上下文。这就是我现在所在的地方;卡住了。

using System;

class DateEx 
{
    static bool hasFormatted = false;

    //empty constructor not required
    //public DateEx(){}

    //make the struct nullable
    public string formatDate(DateTime? myDate = null) 
    {
        //replace the null
        if (!myDate.HasValue)
        {
        myDate = DateTime.Now;
        }

        //if (myDate == null) 
        //  myDate = new DateTime(DateTime.Year, DateTime.Month, DateTime.Day);

        if (hasFormatted == true) 
        {
            return "The date " + myDate + " is already formatted.";
        }
        else 
        {
            return String.Format("0:m/d/yyyy",  myDate);
        }
    return myDate;
    }
}

我意识到这与 class 有关,它将切断它存在的 DateTime 的时间部分。在我看来,这并没有多大意义,除非除了纠正问题之外,还添加或可能移动了新的代码行?我在第 5 个小时试图解决这个问题,因为我正在做这个 post.

当我在 www.ideone.com 上通过 C# 编译器 运行 我的上述代码时,我得到的剩余错误是:

Compilation error   time: 0 memory: 0 signal:0
prog.cs(30,12): error CS0029: Cannot implicitly convert type `System.DateTime?' to `string'
error CS5001: Program `prog.exe' does not contain a static `Main' method suitable for an entry point
Compilation failed: 2 error(s), 0 warnings

如有任何想法,我们将不胜感激。

我希望你用控制台应用程序试过这个,如果是的话你的 class 应该有下面的 method.this 是因为 main() 方法是入口点。

 public void Main(string[] args)
    {
    }

你应该在这个方法中编写你的代码。 请看下面的代码

public class Program
{
    static bool hasFormatted = false;
    public void Main(string[] args)
    {
        formatDate();
    }
    public string formatDate(DateTime? myDate = null)
    {

        string formateddDate;
        //replace the null
        if (!myDate.HasValue)
        {
            myDate = DateTime.Now;
        }

        //if (myDate == null) 
        //  myDate = new DateTime(DateTime.Year, DateTime.Month, DateTime.Day);

        if (hasFormatted == true)
        {
            return "The date " + myDate + " is already formatted.";
        }
        else
        {
             formateddDate= String.Format("{0:m/dd/yyyy}", myDate);
        }
        return formateddDate;
    }
}

鉴于简短示例中语法错误和约定违规的数量,我认为其目的是了解您对该语言的语法及其命名约定了解多少。

逐行进行,这就是您所拥有的:

  1. 缺少大括号
  2. 错误的数据类型、非常规名称、错误的赋值运算符和缺少分号
  3. 这一行完全是非法的(你知道为什么吗?)
  4. 方法的非常规名称,以及使用默认参数的无效尝试(您知道为什么吗?)
  5. if 语句语法完全错误,相等比较运算符错误 ==
  6. 在字符串文字中使用双引号的方式不正确
  7. 第 9 行的不平衡大括号缺少左大括号
  8. string.Format 的参数之间缺少分隔符,方法名称大写错误
  9. 好的
  10. 正在尝试 return 类型错误的对象
  11. 好的
  12. (缺少此行)class
  13. 需要一个右大括号