C#4默认参数值:如何分配默认的DateTime /对象值?
如果DateTime是一个对象,并且默认的C#参数只能被赋予编译时常量,那么如何为像DateTime这样的对象提供默认值?
我想用一个构造函数初始化一个POCO中的值,使用具有默认值的命名参数。
 DateTime不能用作常量,但是可以将其设置为可空types( 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(); 
 您可以直接执行此操作的唯一方法是使用default(DateTime) ,这是编译时常量。 或者你可以通过使用DateTime? 并将默认值设置为null 。 
 另请参阅有关TimeSpan相关问题 。 
新的DateTime()也等于DateTime.MinValue
你可以创build一个像这样的默认参数。
 void test(DateTime dt = new DateTime()) { //... } 
与VB不同,C#不支持date文字。 由于可选参数在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 
你可以使用:
 Datetime.MinValue 
进行初始化。
 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);