(SOLVED) Sto creando un'applicazione che può creare dinamicamente parte del suo controllo, in base ad una descrizione del file XML.
Quello che mi serve ora è qualcosa di molto simile al metodo TryParse(): una possibilità di controllare (senza lanciare/catturare un'eccezione), se un testo nella variabile stringa può essere convertito (o analizzato) in un tipo, quale nome ho in altre variabe (myType
).
Il problema è che myType
può essere uno qualsiasi dei tipi .NET: DateTime, Bool, Double, Int32
eccVerifica se la stringa può essere convertita in altro tipo diverso
Esempio:
string testStringOk = "123";
string testStringWrong = "hello";
string myType = "System.Int32";
bool test1 = CanCovertTo(testStringOk, myType); //true
bool test2 = CanCovertTo(testStringWrong, myType); //false
Come funziona CanCovertTo(string testString, string testType)
funzione dovrebbe essere simile?
Il più vicino che ottenga è seguente codice:
private bool CanCovertTo(string testString, string testType)
{
Type type = Type.GetType(testType, null, null);
TypeConverter converter = TypeDescriptor.GetConverter(type);
converter.ConvertFrom(testString); //throws exception when wrong type
return true;
}
tuttavia, viene generata un'eccezione durante il tentativo di convertire da stringa di sbagliato, e preferisco non usare try {} catch()
per questo.
Soluzione:
private bool CanCovertTo(string testString, string testType)
{
Type type = Type.GetType(testType, null, null);
TypeConverter converter = TypeDescriptor.GetConverter(type);
return converter.IsValid(testString);
}
Perché preferisci non usare try/catch per questo? – PVitt
Perché stai provando a convertire un valore in una funzione che si chiama CanConvert? Non puoi semplicemente fare "return converter.CanConvertFrom (typeof (string))" – Grrbrr404
@PVitt: si tratta solo di "best practice", ho letto che dovresti evitare di lavorare con le eccezioni con le normali azioni del programma. Credo che sia il motivo per cui il metodo TryParse() esiste insieme a Parse(). Onestamente, se c'è un metodo migliore di questo, che mi permette di fare ciò di cui ho bisogno, preferisco quello. :) – mj82