Usted puede utilizar el operador params
parámetro para pasar una lista de parámetros nulos:
public static void ThrowIfNull(params object[] input)
{
foreach (var item in input)
{
//Your choice of how you want to handle this. I chose an exception.
throw new NullReferenceException();
}
}
que le permitirá a:
int? nullableInt = null;
string someNullString = null;
ThrowIfNull(nullableInt, someNullString);
También hay otras maneras de abordar este problema . Por ejemplo, puede crear un método de extensión para IEnumerable
:
public static class NullExtensionMethods
{
public static void ThrowIfHasNull<T>(this IEnumerable collection)
where T : Exception, new()
{
foreach (var item in collection)
{
if (item == null)
{
throw new T();
}
}
}
public static void ThrowIfHasNull(this IEnumerable collection)
{
ThrowIfHasNull<NullReferenceException>(collection);
}
}
hacer esto posible:
string someNullString = null;
new string[] { someNullString }.ThrowIfHasNull();
//or for context specific exceptions
new string[] { someNullString }.ThrowIfHasNull<ArgumentNullException>();
Aunque yo prefiero evitar excepciones siempre que sea posible. Se pueden realizar los siguientes cambios:
public static class NullExtensionMethods
{
public static bool HasNull(this IEnumerable collection)
{
foreach (var item in collection)
{
if (item == null)
{
return true;
}
}
return false;
}
}
Lo que le permite manejar las cosas mucho más gracia:
var nullDetected = new string[] { someNullString }.HasNull();
Puesto que estamos utilizando métodos de extensión, que puede explotar aún más la función mediante la adición de sobrecargas para casos específicos. Entonces, por ejemplo, una cadena vacía se puede tratar de la misma manera String.IsNullOrEmpty
. En este caso me gustaría añadir un método de extensión adicional HasNullOrEmpty
:
public static bool HasNullOrEmpty(this IEnumerable<string> collection)
{
foreach (var item in collection)
{
if (string.IsNullOrEmpty(item))
{
return true;
}
}
return false;
}
Aunque el comercio es que el tipo debe ser IEnumerable<string>
'foreach' requiere que estén en un' IEnumerable'. Si desea específicamente 'foreach', tendrá que poner cada uno de ellos en una colección. –
¿Está buscando verificar las variables ** ALL ** en la función local o solo un subconjunto? –
@ p.campbell en realidad para ser precisos, foreach necesita un IEnumerable –