C # 4 valores de parámetros predeterminados: ¿Cómo asignar un valor de DateTime/object predeterminado? [duplicar]
Esta pregunta ya tiene una respuesta aquí:
- C# 4.0: ¿Puedo usar un intervalo de tiempo como parámetro opcional con un valor predeterminado? 8 respuestas
Si DateTime es un objeto y los parámetros predeterminados de C# solo se pueden asignar constantes de tiempo de compilación, ¿cómo proporciona valores predeterminados para objetos como DateTime?
Estoy tratando de inicializar valores en un POCO con un constructor, usando parámetros nombrados con valores predeterminados.
6 answers
DateTime
no se puede usar como una constante, pero podría convertirla en un tipo nullable (DateTime?
) en su lugar.
Dé a DateTime?
un valor predeterminado de null
, y si se establece en null
al inicio de su función, entonces puede inicializarlo a cualquier valor que desee.
static void test(DateTime? dt = null)
{
if (dt == null)
{
dt = new DateTime(1981, 03, 01);
}
//...
}
Puedes llamarlo con un parámetro llamado como este:
test(dt: new DateTime(2010, 03, 01));
Y con el parámetro por defecto como este:
test();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-24 03:30:25
La única forma de hacer esto directamente es usar el valor default(DateTime)
, que es constante en tiempo de compilación. O puede solucionar esto usando DateTime?
y estableciendo el valor predeterminado en null
.
Ver también esta pregunta relacionada sobre TimeSpan
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:12
New DateTime() también es igual a DateTime.MinValue
Podría crear un parámetro predeterminado como este.
void test(DateTime dt = new DateTime())
{
//...
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-30 21:56:48
A diferencia de VB, C# no admite literales de fecha. Y dado que los parámetros opcionales se ven así en IL, no se puede falsificar con atributos.
.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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-10 22:36:20
private System.String _Date= "01/01/1900";
public virtual System.String Date
{
get { return _Date; }
set { _Date= value; }
}
Podemos asignar un valor a una etiqueta como se indica a continuación,
lblDate.Text = Date;
También podemos obtener el valor,
DateTime dt = Convert.ToDateTime(label1.Text);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-09 10:16:44
Podrías usar:
Datetime.MinValue
Para inicialización.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-05 10:22:12