Puedo formatear valores NULOS en cadena.Formato?


Me preguntaba si hay una sintaxis para formatear valores NULOS en string.Formato, como lo que usa Excel

Por ejemplo, usando Excel podría especificar un valor de formato de {0:#,000.00;-#,000.00,NULL}, lo que significa mostrar el valor numérico como formato de número si es positivo, formato de número entre paréntesis si es negativo o NULO si el valor es nulo

string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);

Editar

Estoy buscando formato NULL/Nothing valores para todos los tipos de datos, no solo los numéricos.

Mi ejemplo es realmente incorrecto porque erróneamente pensé que Excel usaba el 3er parámetro si el valor era NULO, pero en realidad se usa cuando el valor es 0. Lo dejo ahí porque es lo más parecido que se me ocurre a lo que esperaba hacer.

Espero evitar el operador coalescente nulo porque estoy escribiendo registros de registro, y los datos no suelen ser una cadena

Sería mucho más fácil escribir algo como

Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}", 
    new object[] { oldObject.SomeValue, newObject.SomeValue }));

Que escribir

var old = (oldObject.SomeValue == null ? "null" : oldObject.SomeValue.ToString());
var new = (newObject.SomeValue == null ? "null" : newObject.SomeValue.ToString());

Log(string.Format("Value1 changes from {0} to {1}", 
    new object[] { old, new }));
Author: Rachel, 2011-10-07

5 answers

Puede definir un formateador personalizado {[7] } que devuelve "NULL" si el valor es null y de lo contrario la cadena formateada por defecto, por ejemplo:

foreach (var value in new[] { 123456.78m, -123456.78m, 0m, (decimal?)null })
{
    string result = string.Format(
        new NullFormat(), "${0:#,000.00;(#,000.00);ZERO}", value);
    Console.WriteLine(result);
}

Salida:

$123.456,78
$(123.456,78)
$ZERO
$NULL

Formateador Personalizado:

public class NullFormat : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type service)
    {
        if (service == typeof(ICustomFormatter))
        {
            return this;
        }
        else
        {
            return null;
        }
    }

    public string Format(string format, object arg, IFormatProvider provider)
    {
        if (arg == null)
        {
            return "NULL";
        }
        IFormattable formattable = arg as IFormattable;
        if (formattable != null)
        {
            return formattable.ToString(format, provider);
        }
        return arg.ToString();
    }
}
 30
Author: dtb,
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-10-07 15:20:58

No creo que haya nada en String.Format que te permita especificar un formato particular para null cadenas. Una solución es usar el operador null-coalescing , así:

const string DefaultValue = "(null)";

string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);
 11
Author: Jim Mischel,
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-10-07 19:30:59

¿Es esto lo que quieres?

string test;

Prueba ?? "NULL"

 2
Author: Karel,
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-10-07 15:07:57

Se parece a String.El formato para. NET actúa de la misma manera que Excel, es decir, puede usar el separador ; para valores positivos, negativos y 0, pero no NULO: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator .

Probablemente solo tendrá que manejar el valor nulo manualmente:

if (myval == null)
    // handle
else
    return String.Format(...);
 1
Author: mellamokb,
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-10-07 15:08:45

Podría usar un método de extensión:

 public static string ToDataString(this string prm)
   {
       if (prm == null)
       {
           return "NULL";
       }
       else
       {
           return "'" + prm.Replace("'", "''") + "'";
       }
   }

Entonces en tu código puedes hacer:

string Field1="Val";
string Field2=null;

string s = string.Format("Set Value:{0}, NullValue={1}",Field1.ToDataString(), Field2.ToDataString());
 0
Author: Black White,
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-06-23 21:15:32