napisałem poniżej metody z follwing wymogu -Typowa metoda powrotu pustych typ wartości
- wejście jest XMLNode i attributeName
- Zwraca wartość, jeśli jest z powiązanej nazwy atrybutu przeszedł znaleziono
Tam, gdzie nie ma wartości w attributeName, należy ją zwrócić -
3.1. Dla int -1 3.2. Dla Datetime DateTime.MinValue 3.3. W przypadku łańcucha ciągów, nr 3.4. Dla bool, null
Poniższa metoda kończy się niepowodzeniem dla przypadku 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));
}
Kiedy zmiana to
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));
}
To nie dla typu string tj przypadku 3,3
szuka pomocy przodu.
Jak uruchomić metodę w swoim pierwszym zbiorze? Musiałbyś nazwać to jako 'AttributeValue (...)' Jeśli po prostu wywołasz 'AttributeValue (...)' to 'null' nie jest poprawną wartością' bool'. EDYCJA: A twoja druga sprawa kończy się niepowodzeniem, ponieważ 'ciąg' nie może być użyty dla' System.Nullable 'ponieważ' string' nie jest strukturą typu wartości. –