È possibile utilizzare l'operatore params
parametro da passare un elenco di parametri nulli:
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();
}
}
, che vi permetterà di:
int? nullableInt = null;
string someNullString = null;
ThrowIfNull(nullableInt, someNullString);
Ci sono anche altri modi per affrontare questo problema . Per esempio è possibile creare un metodo di estensione per 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);
}
}
Rendere possibile tutto ciò:
string someNullString = null;
new string[] { someNullString }.ThrowIfHasNull();
//or for context specific exceptions
new string[] { someNullString }.ThrowIfHasNull<ArgumentNullException>();
Anche se io preferisco evitare eccezioni, ove possibile. È possibile apportare le seguenti modifiche:
public static class NullExtensionMethods
{
public static bool HasNull(this IEnumerable collection)
{
foreach (var item in collection)
{
if (item == null)
{
return true;
}
}
return false;
}
}
Consentendo di gestire le cose molto più garbo:
var nullDetected = new string[] { someNullString }.HasNull();
Dal momento che stiamo usando metodi di estensione, siamo in grado di sfruttare ulteriormente la funzionalità con l'aggiunta di sovraccarichi per casi specifici. Ad esempio, una stringa vuota può essere trattata allo stesso modo String.IsNullOrEmpty
. In questo caso vorrei aggiungere un metodo di estensione in più HasNullOrEmpty
:
public static bool HasNullOrEmpty(this IEnumerable<string> collection)
{
foreach (var item in collection)
{
if (string.IsNullOrEmpty(item))
{
return true;
}
}
return false;
}
Anche se il commercio è che il tipo deve essere IEnumerable<string>
'foreach' richiede che siano in un' IEnumerable'. Se vuoi specificamente 'foreach', dovrai inserire ognuno di questi in una raccolta. –
Stai cercando di controllare ** ALL ** variabili nella funzione locale o solo un sottoinsieme? –
@ p.campbell in realtà per essere precisi foreach ha bisogno di un IEnumerable –