ho scritto qui di seguito il metodo con il requisito follwing -metodo generico per tornare Nullable Tipo Valori
- ingresso è xmlnode e attributeName
- di ritorno il valore se si trova con il nome dell'attributo associato passato
Dove non è stato assegnato alcun valore in attributeName, deve restituire -
3.1. Per int -1 3.2. Per Datetime DateTime.MinValue 3.3. Per String, null 3.4. Per bool, null
Sotto il metodo non riesce per il caso 3.4.
public T AttributeValue<T>(XmlNode node, string attributeName)
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
value = null;
else if (typeof(T) == typeof(bool))
value = null;
}
return (T)Convert.ChangeType(value, typeof(T));
}
Quando il cambiamento che questo
public System.Nullable<T> AttributeValue<T>(XmlNode node, string attributeName) where T : struct
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
return null;
else if (typeof(T) == typeof(bool))
return null;
}
return (T?)Convert.ChangeType(value, typeof(T));
}
Non riesce per tipo di stringa cioè caso 3,3
Guardando avanti per un po 'di aiuto.
Come si chiama _call_ il metodo nel primo set di codice? Dovresti chiamarlo come 'AttributeValue (...)' Se chiami semplicemente 'AttributeValue (...)' allora 'null' non è un valore valido per' bool'. EDIT: E il tuo secondo caso fallisce perché 'stringa' non può essere usato per' System.Nullable 'perché' stringa' non è una struttura di tipo valore. –