【发布时间】:2011-02-23 02:02:52
【问题描述】:
如果 DateTime 是一个对象,并且默认 C# 参数只能分配编译时常量,那么如何为 DateTime 之类的对象提供默认值?
我正在尝试使用带有默认值的命名参数通过构造函数初始化 POCO 中的值。
【问题讨论】:
-
调用设置参数的重载方法:stackoverflow.com/a/3031309/492
标签: c# default-parameters
如果 DateTime 是一个对象,并且默认 C# 参数只能分配编译时常量,那么如何为 DateTime 之类的对象提供默认值?
我正在尝试使用带有默认值的命名参数通过构造函数初始化 POCO 中的值。
【问题讨论】:
标签: c# default-parameters
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();
【讨论】:
DateTime dt = default(DatetTime)
您可以直接执行此操作的唯一方法是使用值default(DateTime),它是编译时常量。或者您可以通过使用DateTime? 并将默认值设置为null 来解决此问题。
【讨论】:
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
用于初始化。
【讨论】: