我寫了下面的方法與follwing要求 -返回可空類型通用的方法值
- 輸入的XMLNode和的attributeName
- 回報,一旦發現與傳遞 相關的屬性名稱值
如果在傳遞的attributeName中沒有值,則應返回 -
3.1。對於int -1 3.2。對於日期時間DateTime.MinValue 3.3。對於字符串,null 3.4。對於布爾,null
下面的方法在案例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));
}
當改變這
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));
}
它無法爲字符串類型,即3.3的情況下
期待一些幫助。
你如何_call_在你的第一套代碼中的方法?您需要將它稱爲'AttributeValue(...)'如果您只是調用'AttributeValue (...)',那麼'null'不是'bool'的有效值。編輯:而你的第二種情況失敗,因爲'字符串'不能用於'System.Nullable '因爲'字符串'不是一個值類型的結構。 –