如果 DateTime 是一个对象,并且默认 C# 参数只能分配编译时常量,那么如何为 DateTime 等对象提供默认值?
我正在尝试使用具有默认值的命名参数来使用构造函数初始化 POCO 中的值。
如果 DateTime 是一个对象,并且默认 C# 参数只能分配编译时常量,那么如何为 DateTime 等对象提供默认值?
我正在尝试使用具有默认值的命名参数来使用构造函数初始化 POCO 中的值。
DateTime
不能用作常量,但您可以将其设为可空类型 ( DateTime?
)。
给DateTime?
一个默认值null
,如果它null
在你的函数开始时设置为,那么你可以将它初始化为你想要的任何值。
static void test(DateTime? dt = null)
{
if (dt == null)
{
dt = new DateTime(1981, 03, 01);
}
//...
}
您可以使用这样的命名参数调用它:
test(dt: new DateTime(2010, 03, 01));
并使用这样的默认参数:
test();
您可以直接执行此操作的唯一方法是使用 value default(DateTime)
,它是编译时常量。或者,您可以通过使用DateTime?
并将默认值设置为null
.
另请参阅有关TimeSpan
.
new DateTime() 也等于 DateTime.MinValue
您可以像这样创建一个默认参数。
void test(DateTime dt = new DateTime())
{
//...
}
与 VB 不同,C# 不支持日期文字。而且由于可选参数在 IL 中看起来像这样,因此您不能使用属性来伪造它。
.method private hidebysig static void foo([opt] int32 x) cil managed
{
.param [1] = int32(5)
.maxstack 8
L_0000: nop
L_0001: ret
}
.method //this is a new method
private hidebysig static //it is private, ???, and static
void foo //it returns nothing (void) and is named Foo
([opt] int32 x) //it has one parameter, which is optional, of type int32
.param [1] = int32(5) //give the first param a default value of 5
private System.String _Date= "01/01/1900";
public virtual System.String Date
{
get { return _Date; }
set { _Date= value; }
}
我们可以为标签赋值,如下所示,
lblDate.Text = Date;
我们也可以获得价值,
DateTime dt = Convert.ToDateTime(label1.Text);
你可以使用:
Datetime.MinValue
用于初始化。