2012-11-22 3 views
5

Non posso credere che non possa google questo. Non so cosa google.C#: Controlla se il tipo T è bool

public static T GetValue<T>(T defaultValue) 
{ 
    if (T is bool) // <-- what is the correct syntax here? 
    return (T)true; // <-- I don't think this works either 
} 

MODIFICA: Spiacente di non averlo menzionato, la funzione sopra è solo per mostrare la mia domanda. Non è una funzione reale. Grazie a tutti per le risposte!

+0

Provare a cercare gli errori del compilatore. Sono sicuro che ci sono molti duplicati. Per lo meno, * include * [compilatore] errori nelle domande quando applicabile. –

risposta

10

Se uno deve uso questo stesso metodo/firma e devono utilizzano il tipo di T (e ci sono motivo di tanto, anche se non ci sono poi vedere la risposta di Albin):

public static T GetValue<T>(T defaultValue) 
{ 
    // Need to use typeof to get a Type object for bool, just as with T 
    if (typeof(T) == typeof(bool)) { 
    // Need to say "get out of my way C#" 
    // The first cast to object is required as true (bool) is 
    // otherwise not castable to an unrestricted T. 
    // This widen-restrict approach could result in a cast error, 
    // but from the above check it is known that T is bool. 
    return (T)(object)true; 
    } 
    // .. other stuff that .. does stuff. 
} 

Tuttavia, restituire esplicitamente true (che non è il valore predefinito per un valore booleano) e ignorare completamente defaultValue sembra .. sospetto. Ma - It compiles! Ship it!

Note:

  • L'uso == per i Tipi sarà non funzionare in modo affidabile per sottoclassi (ma va bene perché bool è una struttura così sottotipi non sono un problema). In questi casi, guarda IsAssignableFrom.
  • typeof(T) non è necessariamente il tipo del valore passato (che potrebbe essere null per i tipi di riferimento). Questo, insieme ai sottotipi, può portare a sottili variazioni degli approcci che usano il valore is.
+0

+1 per indicare il problema di questa soluzione per i sottotipi. Ho passato ore su un problema del genere una volta. – Guillaume

7

Non controllare il tipo, controllare la variabile

public static T GetValue<T>(T defaultValue) 
{ 
    if (defaultValue is bool) // <-- what is the correct syntax here? 
    return (T)true; 
} 

Ma proprio come un lato non, quando si esegue il controllo di tipo e hanno la manipolazione diversi per i diversi tipi in un tipo generico che si sta facendo qualcosa di sbagliato in genere .

Perché non si crea un sovraccarico per i tipi con gestione speciale?

public static bool GetValue(bool defaultValue) 
{ 
    return true; 
} 
+0

Ah, grazie, ma ho questa funzione che funziona già per tutte le string/int/double/float/decimal eccetto bool – Aximili

+2

'(T) true' non funziona, ovviamente – horgh

3

Forse stai cercando default(T), che restituisce il valore predefinito per il tipo fornito. Il valore predefinito per bool è false.

+1

+1: bella supposizione! – horgh