简体   繁体   English

DateTime.Now在类构造函数中

[英]DateTime.Now in class constructor

Good day all. 美好的一天。
I am working on something that handles tasks. 我正在研究处理任务的事情。
Each task consists of 3 strings and a DateTime Object 每个任务由3个字符串和一个DateTime对象组成

Below is the constructor I built. 下面是我构建的构造函数。

public Task(string von, string was, string an, DateTime zeit = DateTime.Now)

When compiling I get compiler error 编译时我得到编译器错误

Default parameter value for 'zeit' must be a compile-time constant (CS1736)

I assume the problem is, that -obvioulsy- the value for DateTime.Now depends on the time the constructor is called, which is the whole point that I want to have here. 我假设问题是,-obvioulsy- DateTime.Now的值取决于构造函数被调用的时间,这是我想要的全部内容。

I already looked at [this] thread, but it does not really apply to me, because the memory demand for a DateTime Object is always the same and that thread says the problem is the unknown heap-demand of that call. 我已经看过[this]线程,但它并不真正适用于我,因为DateTime对象的内存需求总是相同的,并且该线程说问题是该调用的未知堆需求。 1 1
I already have an idea for a work-around (see below), but as we all know work-arounds are not best practice 我已经有了解决方案的想法(见下文),但我们都知道解决方法不是最佳实践

public Task(string von, string was, string an, DateTime zeit){
    if(zeit == null)
        dateOfCreation = DateTime.Now; //dateOfCreation being the name of Task's internal DateTime field.
    else
        dateOfCretion = zeit;

So if I want to use the current DateTime I pass null. 所以,如果我想使用当前的DateTime,我会传递null。 However: If I take the time and effort to always specifically pass null, I might as well each time pass DateTime.Now. 但是:如果我花时间和精力始终专门传递null,我不妨每次都传递DateTime.Now。

Question: Is there a way to get parameter DateTime zeit = DateTime.Now accepted or substituted with identical outcome? 问题:有没有办法获取参数DateTime zeit = DateTime.Now接受或替换相同的结果?

Use Constructor overloading instead: 使用构造函数重载:

public Task(string von, string was, string an, DateTime zeit)
{
 ...
}

public Task(string von, string was, string an) : this(von, was, an, DateTime.Now)
{
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM